Exemplo n.º 1
0
def top_albums_short():
    sp = get_spotify_object()

    top_albums = []

    history = []
    # keep get top tracks until there is no more left
    offset_count = 0
    limit_count = 50
    while (True):
        top_tracks_raw = sp.current_user_top_tracks(limit=limit_count,
                                                    offset=offset_count,
                                                    time_range='short_term')
        offset_count += limit_count

        for one_track in top_tracks_raw['items']:
            cur_album = one_track['album']
            cur_album_id = one_track['album']['id']

            if cur_album_id not in history:
                top_albums.append(cur_album)
                # make sure they don't repeat
                history.append((cur_album_id))

        # if there are less tracks then limit_count, then no need to do another search
        if len(top_tracks_raw['items']) < limit_count:
            break

    return {"top_albums_short": top_albums}
Exemplo n.º 2
0
def track_audio_analysis(track_id):

    sp = get_spotify_object()

    audio_analysis = sp.audio_analysis(track_id)

    return {'track_audio_analysis': audio_analysis}
Exemplo n.º 3
0
def top_tracks_audio_features():

    sp = get_spotify_object()

    ids = get_track_ids()

    audio_features = sp.audio_features(ids)

    return {'top_tracks_audio_features': audio_features}
Exemplo n.º 4
0
def get_track_audio_features(track_id):

    sp = get_spotify_object()

    track = []
    track.append(track_id)

    audio_features = sp.audio_features(track)

    return {'track_audio_features': audio_features}
Exemplo n.º 5
0
def track_preview_url(track_id):
    sp = get_spotify_object()
    track_details = sp.track(track_id)
    track_preview_link = track_details['preview_url']

    # some tracks do not have preview url
    if not track_preview_link:
        return "false"

    return track_preview_link
Exemplo n.º 6
0
def get_user_playlist(playlist_id):
    sp = get_spotify_object()

    user_playlist = []

    playlist_tracks = sp.playlist_tracks(playlist_id)

    for track in playlist_tracks['items']:
        user_playlist.append(track)

    return {'playlist_tracks': user_playlist}
Exemplo n.º 7
0
def get_track_ids():
    sp = get_spotify_object()

    ids = []

    top_tracks = sp.current_user_top_tracks(limit=50, offset=0)

    for one_track in top_tracks['items']:
        one_track_id = one_track['id']
        ids.append(one_track_id)

    return ids
Exemplo n.º 8
0
def redirect_page():
    sp_oauth = get_spotify_oauth()
    session.clear()

    # get the code passed back with the query string, it's needed to get the access token
    code = request.args.get('code')

    # if no code is given, that means user chose "decline" not "agree"
    if code is None:
        try:
            del session['TOKEN_INFO']
        finally:
            return redirect("/", 403)

    # get token info (access token included) with the code
    token_info = sp_oauth.get_access_token(code, check_cache=False)

    # save token info into the session
    session['TOKEN_INFO'] = token_info

    # FIXME
    refresh_token_info(token_info['refresh_token'])

    # try to login the user in
    try:
        # get spotify object that we will make request of
        sp = get_spotify_object()
        cur_user = sp.current_user()
        cur_user_name = cur_user['display_name']
        cur_user_id = cur_user['id']
        cur_user_email = cur_user['email']

        # FIXME: may need more info later
        db_user = User.query.filter(User.user_id == cur_user_id).first()
        if not db_user:
            db_user = User(user_name=cur_user_name,
                           user_id=cur_user_id,
                           user_email=cur_user_email)
            db.session.add(db_user)
            db.session.commit()

        #FIXME: may need more details later
        elif db_user.banned:
            return "You are banned", 403

        #login user
        login_user(db_user)

    except Exception as e:
        print(e)

    #refer to the /home in front end route
    return redirect("/home")
Exemplo n.º 9
0
    def get_json(self):
        if is_new(self.update_datetime, timedelta(minutes=5)):
            return self.info_json

        # else update by calling api
        sp = get_spotify_object()
        new_json_info = sp.current_user()

        self.info_json = new_json_info
        self.update_datetime = datetime.utcnow()

        db.session.commit()

        return self.info_json
Exemplo n.º 10
0
def get_playlist_audio_features(playlist_id):

    sp = get_spotify_object()

    playlist_track_ids = []

    playlist_tracks = sp.playlist_tracks(playlist_id)

    for track in playlist_tracks['items']:
        one_track_id = track['track']['id']
        playlist_track_ids.append(one_track_id)

    audio_features = sp.audio_features(playlist_track_ids)

    return {'playlist_audio_features': audio_features}
Exemplo n.º 11
0
def playback_current():
    sp = get_spotify_object()
    raw_data_json = sp.current_playback()

    # FIXME: change this if return null json data is not valid
    # only get return value when user is playing or just paused
    if not raw_data_json:
        return {}

    return {
        "progress": raw_data_json['progress_ms'],
        "total_length": raw_data_json['item']['duration_ms'],
        "is_playing": raw_data_json['is_playing'],
        "playback_json": raw_data_json
    }
Exemplo n.º 12
0
    def get_json(self):
        if is_new(self.timestamp, timedelta(hours=1)):
            return self.info_json

        # else update by calling api
        sp = get_spotify_object()
        new_json_info = sp.current_user_top_tracks(limit=50,
                                                   time_range='long_term')

        self.info_json = new_json_info
        self.timestamp = datetime.utcnow()
        db.session.commit()

        print("---in db, updating user top tracks info...")

        return self.info_json
Exemplo n.º 13
0
    def get_json(self):
        if is_new(self.timestamp, timedelta(minutes=5)):
            return self.info_json

        # else update by calling api
        sp = get_spotify_object()
        new_json_info = sp.current_user_recently_played(limit=50)

        self.info_json = new_json_info
        self.timestamp = datetime.utcnow()

        db.session.commit()

        print("---in db, updating user recent tracks info...")

        return self.info_json
Exemplo n.º 14
0
    def __get_json(self):
        if is_new(self.timestamp, timedelta(weeks=1)):
            return self.info_json

        # else update by calling api
        sp = get_spotify_object()
        new_info_json = sp.album(self.album_id)

        self.timestamp = datetime.utcnow()
        self.info_json = new_info_json
        self.album_name = new_info_json['name']

        # since the caller is itself, do commit itself
        db.session.commit()

        print("---in db, updating album info...")

        return self.info_json
Exemplo n.º 15
0
def set_playlist():

    sp = get_spotify_object()
    if request.method == "POST":
        data_json = request.get_json()
        playlistID = data_json['playlistID']
        privacy = data_json['privacy']
        user = data_json['user']

        if privacy == 'private':
            privacy = True
        else:
            privacy = False

        sp.user_playlist_change_details(playlist_id=playlistID,
                                        public=privacy,
                                        user=user)
        return {}
Exemplo n.º 16
0
def redirect_page():
    sp_oauth = get_spotify_oauth()
    session.clear()

    # get the code passed back with the query string, it's needed to get the access token
    code = request.args.get('code')

    # if no code is given, that means user chose "decline" not "agree"
    if code is None:
        try:
            del session['TOKEN_INFO']
        finally:
            # FIXME: need a page I guess
            return 'Authorization failed'

    # get token info (access token included) with the code
    token_info = sp_oauth.get_access_token(code, check_cache=False)

    # save token info into the session
    session['TOKEN_INFO'] = token_info

    # FIXME
    refresh_token_info(token_info['refresh_token'])

    # try to login the user in
    try:
        # get spotify object that we will make request of
        sp = get_spotify_object()
        cur_user = sp.current_user()
        cur_user_name = cur_user['display_name']
        cur_user_id = cur_user['id']

        # FIXME: databaseneeded

        session['LOGGED_IN'] = True
        session['USER_NAME'] = cur_user_name
        session['USER_ID'] = cur_user_id

    except Exception as e:
        print(e)

    return redirect(url_for('user.home', _external=True))
Exemplo n.º 17
0
def recommended_tracks():
    sp = get_spotify_object()

    tracks = []

    top_tracks_raw = sp.current_user_top_tracks(limit=5)

    for one_track in top_tracks_raw['items']:
        tracks.append(one_track['id'])

    # generate recommendation based on 5 top tracks (5 is max)
    recommended_tracks_raw = sp.recommendations(seed_tracks=tracks)

    result = [one_track for one_track in recommended_tracks_raw['tracks']]

    track_uris = [
        one_track['uri'] for one_track in recommended_tracks_raw['tracks']
    ]

    return {"recommended_tracks": result, "uris": track_uris}
Exemplo n.º 18
0
def playlists():
    sp = get_spotify_object()

    # if request is get, return all the playlists current user has
    if request.method == 'GET':
        user_playlists = []

        offset_count = 0
        limit_count = 50
        while (True):
            user_playlists_raw = sp.current_user_playlists(limit=limit_count,
                                                           offset=offset_count)
            offset_count += limit_count

            for one_playlist in user_playlists_raw['items']:
                user_playlists.append(one_playlist)

            if len(user_playlists_raw['items']) < limit_count:
                break

        return {"playlists": user_playlists}

    # -----else if request is post, create a new playlist based on the json given
    if request.method == "POST":
        data_json = request.get_json()
        user_id = current_user.user_id
        playlist_name = data_json['name']
        public = data_json['public']
        # list of tracks' ids
        tracks = data_json['tracks']

        playlist_raw = sp.user_playlist_create(user=user_id,
                                               name=playlist_name,
                                               public=public)
        playlist_id = playlist_raw['id']

        # store the tracks
        return sp.user_playlist_add_tracks(user=user_id,
                                           playlist_id=playlist_id,
                                           tracks=tracks)
Exemplo n.º 19
0
def playlist_details(playlist_id):
    sp = get_spotify_object()

    playlist_details_raw = sp.playlist(playlist_id)

    return playlist_details_raw