Ejemplo n.º 1
0
def search():
    query = request.args.get('query', None)
    if not query:
        raise APIException('You must specify a search query')

    if len(query) < 3:
        return jsonify(success=True, results=[])

    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    data = {
        'method': 'search',
        'query': query,
        'types': 'track',
    }

    try:
        results = rdio_manager.call_api(data)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to search music: %s' % str(e))

    return jsonify(success=True, results=results['results'])
Ejemplo n.º 2
0
def get_tracks(album_id):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    try:
        albums = rdio_manager.get([album_id], ['trackKeys'])
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to retrieve albums: %s' % str(e))

    tracks = []

    if len(albums) > 0:
        if hasattr(albums[0], 'track_keys') and len(albums[0].track_keys) > 0:
            try:
                response = rdio_manager.get(albums[0].track_keys,
                                            ['radioKey', 'streamRegions'])
            except Exception as e:
                current_app.logger.debug(e)
                raise APIException('Unable to retrieve album tracks: %s' %
                                   str(e))

            trackDict = {}
            for track in response:
                trackDict[track.key] = track._data

            tracks = []
            for trackKey in albums[0].track_keys:
                tracks.append(trackDict[trackKey])

    return jsonify(success=True, data=tracks)
Ejemplo n.º 3
0
def get_tracks(playlist_id):
  rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
    current_app.config['RDIO_CONSUMER_SECRET'],
    current_user.oauth_token,
    current_user.oauth_token_secret)

  try:
    playlists = rdio_manager.get([playlist_id], ['trackKeys'])
  except Exception as e:
    current_app.logger.debug(e)
    raise APIException('Unable to retrieve playlist tracks: %s' % str(e))

  if not playlists:
    return []

  playlist = playlists[0]

  if not hasattr(playlist, 'track_keys') or len(playlist.track_keys) == 0:
    return []

  try:
    tracks = rdio_manager.get(playlist.track_keys, ['radioKey', 'streamRegions'])
  except Exception as e:
    current_app.logger.debug(e)
    raise APIException('Unable to retrieve playlist tracks: %s' % str(e))

  tracks = [track._data for track in tracks]

  return jsonify(success=True, data=tracks)
Ejemplo n.º 4
0
def get_playlist_type(list_type):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    if list_type not in ['owned', 'collab', 'favorites']:
        raise APIException('Invalid list type')

    data = {
        'method': 'getUserPlaylists',
        'user': current_user.external_id,
        'kind': list_type,
        'extras': 'radioKey',
    }

    try:
        response = rdio_manager.call_api_authenticated(data)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to retrieve playlist: %s' % str(e))

    playlists = [
        playlist for playlist in response
        if playlist['key'] != current_user.queue
    ]

    return jsonify(success=True, data=playlists)
Ejemplo n.º 5
0
def get_station_type(station_type):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    methods = {
        'you': {
            'method': 'getStations',
            'user': current_user.external_id,
            'v': '20140512',
        },
        'friends': {
            'method': 'getFriendAndTastemakerStations',
            'v': '20140512',
        },
        'recent': {
            'method': 'getRecentStationsHistoryForUser',
            'user': current_user.external_id,
            'v': '20140512',
        },
        'genre': {
            'method': 'getGenreStations',
            'v': '20140512',
            'genre': request.args.get('genre')
        },
        'top': {
            'method': 'getCuratedContent',
            'curationType': 'top_stations',
            'v': '20140512'
        },
        'new': {
            'method': 'getCuratedContent',
            'curationType': 'new_releases_weekly_station',
        },
        'spotlight': {
            'method': 'getCuratedContent',
            'curationType': 'spotlight',
        }
    }

    if station_type not in methods:
        raise APIException('Invalid station type')

    try:
        response = rdio_manager.call_api_authenticated(methods[station_type])
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to retrieve station: %s' % str(e))

    return jsonify(success=True, data=response['items'])
Ejemplo n.º 6
0
    def get_favorites(self):
        rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                                current_app.config['RDIO_CONSUMER_SECRET'],
                                self.oauth_token, self.oauth_token_secret)

        keys = self.get_favorite_keys()
        keys = [key for key in keys if not key.startswith('tp')]

        if not keys:
            return []

        try:
            response = rdio_manager.get(
                keys, ['radioKey', 'streamRegions', 'albumCount'])
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to retrieve favorites: %s' % str(e))

        favoriteDict = {}
        for favorite in response:
            favoriteDict[favorite.key] = favorite._data

        favorites = []
        for key in keys:
            favorites.append(favoriteDict[key])

        return favorites
Ejemplo n.º 7
0
def room_post_action():
  name = request.json.get('name', None)
  if not name:
    raise APIException('You must specify a room name')

  name_slug = slugify(name)
  slug = name_slug
  count = 0

  room = Room.query.filter(Room.slug == name_slug).first()
  while room:
    count += 1
    slug = "%s-%s" % (name_slug, count)
    room = Room.query.filter(Room.slug == slug).first()

  room = Room(
    name=name,
    slug=slug,
    owner_id=current_user.id
  )

  db.session.add(room)
  db.session.commit()

  response = {
    'success': True,
    'id': room.id,
    'slug': slug
  }

  return jsonify(response)
Ejemplo n.º 8
0
    def get_queue_id(self):
        if self.queue:
            return self.queue

        data = {
            'method': 'getUserPlaylists',
            'user': self.external_id,
        }

        rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                                current_app.config['RDIO_CONSUMER_SECRET'],
                                self.oauth_token, self.oauth_token_secret)

        try:
            results = rdio_manager.call_api_authenticated(data)
            if results:
                for playlist in results:
                    if playlist['name'] == u'Lstn to Rdio':
                        self.queue = playlist['key']
                        break
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to create Lstn playlist: %s' % str(e))

        if not self.queue:
            return None

        db.session.add(self)
        db.session.commit()

        return self.queue
Ejemplo n.º 9
0
def room_id_action(room_id):
  if request.method == 'PUT':
    return room_update_action(room_id)

  if request.method == 'DELETE':
    return room_delete_action(room_id)

  room = Room.query.filter(Room.slug == room_id).first()

  if not room:
    room = Room.query.get(int(room_id))

  if not room:
    raise APIException('Room not found', 404)

  rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
    current_app.config['RDIO_CONSUMER_SECRET'],
    current_user.oauth_token,
    current_user.oauth_token_secret)

  hostname = request.headers['Host']
  if ':' in hostname:
    components = string.split(hostname, ':')
    hostname = components[0]

  try:
    playback = rdio_manager.get_playback_token(hostname)
  except Exception as e:
    current_app.logger.debug(e)
    raise APIException('Unable to retrieve playback credentials: %s' % str(e))

  if not playback:
      raise APIException('Unable to retrieve playback token', 500)

  queue = current_user.get_queue()
  favorites = current_user.get_favorite_keys()

  response = {
    'success': 1,
    'room': room,
    'playback': playback,
    'queue': queue,
    'favorites': favorites,
  }

  return jsonify(response)
Ejemplo n.º 10
0
def user_favorites():
    try:
        favorites = current_user.get_favorites()
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to get your favorites: %s' % str(e))

    return jsonify(success=True, data=favorites)
Ejemplo n.º 11
0
def bulk_add_queue():
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    queue_playlist = current_user.get_queue_id()

    data = request.get_json()

    if not data or 'tracks' not in data:
        raise APIException('Unable to add the tracks to your queue: %s' %
                           str(e))

    if queue_playlist:
        try:
            rdio_manager.add_to_playlist(queue_playlist, data['tracks'])
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to add the tracks to your queue: %s' %
                               str(e))
    else:
        try:
            playlist = rdio_manager.create_playlist('Lstn to Rdio',
                                                    'User Queue for Lstn',
                                                    data['tracks'])
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to add the track to your queue: %s' %
                               str(e))

        # Throw an error if we couldn't create it
        if not playlist:
            raise APIException('Unable to create Rdio playlist', 500)

        queue_playlist = playlist.key

        # Update the user's queue field
        current_user.queue = queue_playlist
        db.session.add(current_user)
        db.session.flush()

    # Get the user's queue
    queue = current_user.get_queue()
    return jsonify(success=True, queue=queue)
Ejemplo n.º 12
0
    def get_queue(self):
        rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                                current_app.config['RDIO_CONSUMER_SECRET'],
                                self.oauth_token, self.oauth_token_secret)

        queue_id = self.get_queue_id()
        if not queue_id:
            return []

        try:
            playlists = rdio_manager.get([queue_id], ['trackKeys'])
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to retrieve your queue: %s' % str(e))

        if not playlists:
            return []

        playlist = playlists[0]

        queue = []
        if not hasattr(playlist, 'track_keys') or len(
                playlist.track_keys) == 0:
            return []

        try:
            tracks = rdio_manager.get(playlist.track_keys,
                                      ['radioKey', 'streamRegions'])
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to retrieve your queue: %s' % str(e))

        trackDict = {}
        for track in tracks:
            data = track._data
            data['in_queue'] = 1

            trackDict[track.key] = data

        queue = []
        for trackKey in playlist.track_keys:
            queue.append(trackDict[trackKey])

        return queue
Ejemplo n.º 13
0
def room_update_action(room_id):
  room = Room.query.filter(Room.slug == room_id).first()

  if not room:
    room = Room.query.get(int(room_id))

  if not room:
    raise APIException('Room not found', 404)

  if room.owner_id != current_user.id:
    raise APIExceition('Forbidden', 403)

  name = request.json.get('name', None)
  if not name:
    raise APIException('You must specify a room name')

  response = {
    'success': True,
    'room': room.to_array(),
  }

  if name == room.name:
    return jsonify(response)

  name_slug = slugify(name)
  slug = name_slug
  count = 0

  found_room = Room.query.filter(Room.slug == name_slug).first()
  while found_room:
    count += 1
    slug = "%s-%s" % (name_slug, count)
    found_room = Room.query.filter(Room.slug == slug).first()

  room.name = name
  room.slug = slug

  db.session.add(room)
  db.session.flush()

  response['room'] = room
  return jsonify(response)
Ejemplo n.º 14
0
def clear_queue():
    if not current_user.queue:
        raise APIException('Unable to clear user queue', 500)

    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    queue = current_user.get_queue()
    if queue:
        tracks = [track['key'] for track in queue]

        try:
            rdio_manager.remove_from_playlist(current_user.queue, tracks)
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to reorder your queue: %s' % str(e))

    return jsonify(success=True)
Ejemplo n.º 15
0
def delete_queue(track_id):
    if not current_user.queue:
        raise APIException('Unable to delete track from non-existant playlist')

    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    index = request.args.get('index', 0)
    try:
        rdio_manager.remove_from_playlist(current_user.queue, [track_id],
                                          index)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to remove that song from your queue: %s' %
                           str(e))

    queue = current_user.get_queue()
    return jsonify(success=True, queue=queue)
Ejemplo n.º 16
0
def update_queue():
    if 'queue' not in request.json:
        raise APIException('You must specify queue data')

    if not current_user.queue:
        raise APIException('Unable to set user queue', 500)

    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    tracks = [track['key'] for track in request.json['queue']]

    if tracks:
        try:
            rdio_manager.set_playlist_order(current_user.queue, tracks)
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to reorder your queue: %s' % str(e))

    return jsonify(success=True)
Ejemplo n.º 17
0
def remove_playlist():
  rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
    current_app.config['RDIO_CONSUMER_SECRET'],
    current_user.oauth_token,
    current_user.oauth_token_secret)

  try:
    playlists = rdio_manager.delete_playlist(playlist_id)
  except Exception as e:
    current_app.logger.debug(e)
    raise APIException('Unable to remove the track from the playlist: %s' % str(e))

  return jsonify(success=True)
Ejemplo n.º 18
0
def get_tracks(station_id):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    data = {
        'method': 'generateStation',
        'station_key': station_id,
        'extras': 'trackKeys,streamRegions',
    }

    try:
        station = rdio_manager.call_api_authenticated(data)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to retrieve station tracks: %s' % str(e))

    current_app.logger.debug(station)

    track_keys = []
    if 'tracks' in station:
        track_keys = [track['key'] for track in station['tracks']]

    tracks = []
    if track_keys:
        try:
            tracks = rdio_manager.get(track_keys,
                                      ['radioKey', 'streamRegions'])
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to retrieve station tracks: %s' %
                               str(e))

        tracks = [track._data for track in tracks]

    return jsonify(success=True, data=tracks)
Ejemplo n.º 19
0
def get_playlist_type(list_type):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    if list_type not in ['owned', 'collab', 'subscribed', 'favorites']:
        raise APIException('Invalid list type')

    data = {
        'method': 'getUserPlaylists',
        'user': current_user.external_id,
        'kind': list_type,
    }

    playlists = {}

    try:
        playlists[list_type] = rdio_manager.call_api_authenticated(data)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to retrieve playlist: %s' % str(e))

    return jsonify(success=True, playlists=playlists)
Ejemplo n.º 20
0
def get_collection_tracks(album_id):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    try:
        response = rdio_manager.get_tracks_for_album_in_collection(
            album_id, current_user.external_id, ['radioKey', 'streamRegions'])
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to retrieve tracks: %s' % str(e))

    tracks = [track._data for track in response]

    return jsonify(success=True, data=tracks)
Ejemplo n.º 21
0
def get_albums(artist_id):
  rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
    current_app.config['RDIO_CONSUMER_SECRET'],
    current_user.oauth_token,
    current_user.oauth_token_secret)

  try:
    response = rdio_manager.get_albums_for_artist(artist_id, False, ['radioKey'])
  except Exception as e:
    current_app.logger.debug(e)
    raise APIException('Unable to retrieve albums: %s' % str(e))

  albums = []
  if len(response) > 0:
    albums = [album._data for album in response]

  return jsonify(success=True, data=albums)
Ejemplo n.º 22
0
def vote(user_id, direction):
    if user_id == current_user.id:
        raise APIException('You are unable to vote for yourself')

    voted_user = User.query.get(int(user_id))
    if not voted_user:
        raise APIException('Unable to find user', 404)

    room_id = request.json.get('room', None)
    if not room_id:
        raise APIException('You must specify a room id')

    room = Room.query.filter(Room.slug == room_id).first()

    if not room:
        room = Room.query.get(int(room_id))

    if not room:
        raise APIException('Unable to find room', 404)

    song_id = request.json.get('song', None)
    if not song_id:
        raise APIException('You must specify a song id')

    remaining = request.json.get('remaining', None)
    if not remaining:
        raise APIException('You must specify a song remaining time')

    remaining = int(remaining)

    voting_key = 'vote_%s_%s_%s_%s' % (current_user.id, user_id, room_id,
                                       song_id)
    voted = r.get(voting_key)
    if voted and voted == direction:
        raise APIException('You have already voted')

    if direction == 'downvote':
        voted_user.points = User.points - 1
    else:
        voted_user.points = User.points + 1

    db.session.add(voted_user)
    db.session.flush()

    r.set(voting_key, direction, remaining)

    return jsonify(success=True)
Ejemplo n.º 23
0
def get_playlists():
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    try:
        playlist_set = rdio_manager.get_playlists()
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to get playlists: %s' % str(e))

    playlists = {
        'owned': [],
        'collab': [],
        'subscribed': [],
        'favorites': [],
    }

    if hasattr(playlist_set, 'owned_playlists'):
        playlists['owned'] = [
            playlist._data for playlist in playlist_set.owned_playlists
            if hasattr(playlist, '_data') and playlist.name != u'Lstn to Rdio'
        ]

    if hasattr(playlist_set, 'collab_playlists'):
        playlists['collab'] = [
            playlist._data for playlist in playlist_set.collab_playlists
            if hasattr(playlist, '_data')
        ]

    if hasattr(playlist_set, 'subscribed_playlists'):
        playlists['subscribed'] = [
            playlist._data for playlist in playlist_set.subscribed_playlists
            if hasattr(playlist, '_data')
        ]

    if hasattr(playlist_set, 'favorites_playlists'):
        playlists['favorites'] = [
            playlist._data for playlist in playlist_set.favorites_playlists
            if hasattr(playlist, '_data')
        ]

    return jsonify(success=True, playlists=playlists)
Ejemplo n.º 24
0
def delete_favorite(track_id):
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    data = {
        'method': 'removeFromFavorites',
        'keys': track_id,
    }

    try:
        rdio_manager.call_api_authenticated(data)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException(
            'Unable to remove that track from your favorites: %s' % str(e))

    return jsonify(success=True)
Ejemplo n.º 25
0
def get_collection_albums(artist_id):
  rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
    current_app.config['RDIO_CONSUMER_SECRET'],
    current_user.oauth_token,
    current_user.oauth_token_secret)

  data = {
    'method': 'getAlbumsForArtistInCollection',
    'artist': artist_id,
    'extras': 'radioKey,-tracks',
  };

  try:
    response = rdio_manager.call_api_authenticated(data)
  except Exception as e:
    current_app.logger.debug(e)
    raise APIException('Unable to retrieve albums: %s' % str(e))

  return jsonify(success=True, data=response)
Ejemplo n.º 26
0
def room_delete_action(room_id):
  room = Room.query.filter(Room.slug == room_id).first()

  if not room:
    room = Room.query.get(int(room_id))

  if not room:
    raise APIException('Room not found', 404)

  if room.owner_id != current_user.id:
    raise APIExceition('Forbidden', 403)

  db.session.delete(room)
  db.session.flush()

  response = {
    'success' : True,
  }

  return jsonify(response)
Ejemplo n.º 27
0
    def get_favorite_keys(self):
        rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                                current_app.config['RDIO_CONSUMER_SECRET'],
                                self.oauth_token, self.oauth_token_secret)

        data = {
            'method': 'getKeysInFavorites',
            'user': self.external_id,
        }

        try:
            response = rdio_manager.call_api_authenticated(data)
        except Exception as e:
            current_app.logger.debug(e)
            raise APIException('Unable to retrieve your favorites: %s' %
                               str(e))

        if not response:
            return []

        return response['keys']
Ejemplo n.º 28
0
def user_collection():
    rdio_manager = rdio.Api(current_app.config['RDIO_CONSUMER_KEY'],
                            current_app.config['RDIO_CONSUMER_SECRET'],
                            current_user.oauth_token,
                            current_user.oauth_token_secret)

    data = {
        'method': 'getArtistsInCollection',
        'user': current_user.external_id,
        'extras': 'albumCount,radioKey,count',
    }

    try:
        response = rdio_manager.call_api_authenticated(data)
    except Exception as e:
        current_app.logger.debug(e)
        raise APIException('Unable to get your collection: %s' % str(e))

    artists = []
    for artist in response:
        artist['length'] = artist['count']
        artists.append(artist)

    return jsonify(success=True, data=artists)