def display_all_spotify_users() -> render_template:
    """
    Display all spotify users
    :return: A rendered template
    """

    # Get all spotify users
    spotify_user_list = SpotifyUser.query.all()

    # Json with all the user data
    user_json_list = {}
    for spotify_user in spotify_user_list:
        # Get a auth token for every spotify user
        oauth_token: SpotifyAuthorisationToken = SpotifyAuthorisationToken(
            refresh_token=spotify_user.refresh_token,
            activation_time=spotify_user.activated_at,
            authorisation_token=spotify_user.oauth_token)

        # Check if token is expired
        if oauth_token.is_expired():
            oauth_token = spotify.reauthorize(oauth_token)
            user_id = spotify.me(oauth_token)["id"]
            update_spotify_user(user_id, oauth_token)

        # Get information from the database and spotify and store it in the json
        user_json_list[spotify_user.spotify_user_id] = spotify.me(oauth_token)
        user_json_list[spotify_user.spotify_user_id][
            "playlist_count"] = Playlist.query.filter(
                Playlist.spotify_user == spotify_user.id).count()

    # Return the rendered template
    return render_template("spotify_user/spotify_users.html",
                           spotify_users=user_json_list,
                           title="Spotify Users")
def display_spotify_user_playlists(spotify_user_id: str):
    """
    Display the playlists of one spotify user
    :param spotify_user_id: The user id of the spotify user
    :return: A rendered template of the page
    """

    # Get the spotify user from the database
    spotify_user: SpotifyUser = SpotifyUser.query.filter(
        SpotifyUser.spotify_user_id == spotify_user_id).first()

    # Check if spotify user exists
    if not spotify_user:
        return render_template("resource_not_found.html", title="404")

    # Get all playlists that are assigned to the spotify user
    playlist_list = Playlist.query.filter(
        Playlist.spotify_user == spotify_user.id).all()

    # Get the token from the user
    oauth_token: SpotifyAuthorisationToken = SpotifyAuthorisationToken(
        spotify_user.refresh_token, spotify_user.activated_at,
        spotify_user.oauth_token)
    # Check if the token is expired
    if oauth_token.is_expired():
        oauth_token = spotify.reauthorize(oauth_token)
        user_id = spotify.me(oauth_token)["id"]
        update_spotify_user(user_id, oauth_token)

    # Build the playlist json by the requests to spotify
    playlist_list_json = {}
    for playlist in playlist_list:
        playlist_list_json[playlist.spotify_id] = modify_playlist_json(
            spotify.playlist(playlist.spotify_id, oauth_token))
        playlist_list_json[playlist.spotify_id][
            "max_song_duration"] = playlist.max_song_length

    # Get the username of the spotify user
    user_name = spotify.me(oauth_token)['display_name']

    playlist_list = spotify.user_playlists(oauth_token)["items"]

    autocomplete_playlist_list = {}
    for playlist in playlist_list:
        if playlist["owner"]["id"] == spotify_user_id:
            try:
                autocomplete_playlist_list[
                    playlist["name"] + " - " +
                    playlist["id"]] = playlist["images"][2]["url"]
            except IndexError:
                autocomplete_playlist_list[playlist["name"] + " - " + playlist[
                    "id"]] = "/static/icons/default_playlist_cover.png"

    return render_template(
        "spotify_user/spotify_user_playlists.html",
        playlist_list_json=playlist_list_json,
        user_name=user_name,
        title=f"{user_name}'s Playlists",
        autocomplete_playlist_list=autocomplete_playlist_list)
示例#3
0
def get_playlist_tracks():
    """
    Get the tracks of a playlist
    :return: The tracks of the playlist as json
    """

    playlist_id = request.args.get('playlist-id')

    if not playlist_id:
        return abort(400, "You did not give a playlist-id")

    auth_token = get_token_by_playlist(playlist_id)

    if not auth_token:
        return abort(400, "No playlist with this id found")

    # Check if expired and update the user
    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    modified_tracks = collect_tracks(playlist_id, auth_token)

    return jsonify(modified_tracks)
示例#4
0
def callback():
    """
    Callback that will be called if the user authorizes the first time
    :return: A redirect to the spotify user home page, 403
    """

    if not current_user.is_admin:
        return abort(403, "You are not authorized to visit the page")

    if request.args.get("error"):
        return jsonify(dict(error=request.args.get("error_description")))
    else:
        callback_state = request.args.get("state")

        if callback_state != spotify_info.state:
            return f"The state was not the same. The returned state was {callback_state}"

    auth_code: str = request.args.get("code")
    auth_token: SpotifyAuthorisationToken = SpotifyAuthorisationToken(
        refresh_token=auth_code, activation_time=int(time.time()))

    # Check if expired and update the user
    auth_token = spotify.reauthorize(auth_token,
                                     grant_type="authorization_code")
    auth_token = spotify.reauthorize(auth_token)
    user_id = spotify.me(auth_token)["id"]
    update_spotify_user(user_id, auth_token)

    # return jsonify(OAuth_Token=auth_token.token, Reauthorization_Token=auth_token.refresh_token)
    return redirect(url_for("admin.spotify_users"))
示例#5
0
def get_playlist():
    """
    Get a playlist
    :return: The json of the playlist
    """

    playlist_id = request.args.get('playlist-id')

    if not playlist_id:
        return abort(400, "You did not give a playlist-id")

    auth_token = get_token_by_playlist(playlist_id)

    if not auth_token:
        return abort(400, "No playlist with this id found")

    # Check if expired and update the user
    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    playlist = spotify.playlist(playlist_id=playlist_id, auth_token=auth_token)
    modified_playlist = modify_playlist_json(playlist)

    return modified_playlist
示例#6
0
def search_for_songs():
    """
    Search for songs and artists
    :return: The search results as json
    """

    playlist_id = request.args.get('playlist-id')

    if not playlist_id:
        return abort(400, "You did not give a playlist-id")

    auth_token = get_token_by_playlist(playlist_id)

    if not auth_token:
        return abort(400, "No playlist with this id found")

    # Check if expired and update the user
    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    search_term = request.args.get('searchterm')

    if search_term is None or search_term == "":
        return abort(400)

    search_results = spotify.search(search_term, "track", auth_token, limit=10)

    return_search_results = modify_track_json(search_results["tracks"])
    return return_search_results
示例#7
0
def me():
    """
    Get information about the auth token for the playlist
    :return: Information about the playlist spotify user
    """

    playlist_id = request.args.get('playlist-id')

    if not playlist_id:
        return abort(400, "You did not give a playlist-id")

    auth_token = get_token_by_playlist(playlist_id)

    if not auth_token:
        return abort(400, "No playlist with this id found")

    # Check if expired and update the user
    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    return spotify.me(auth_token=auth_token)
def add_playlist_to_spotify_user(playlist_id: str, spotify_user_id: str, song_length: int):
    """
    Add a new spotify playlist to a user
    :param song_length: The max song length
    :param spotify_user_id: The spotify user id of the playlist owner
    :param playlist_id: The playlist id
    :return: Status 400 or the playlist json
    """

    # Check if the playlist exists
    if Playlist.query.filter(Playlist.spotify_id == playlist_id).first():
        return abort(400, "The playlist does already exist")

    # Get a random spotify user for a auth token
    temp_user: SpotifyUser = SpotifyUser.query.filter(SpotifyUser.spotify_user_id == spotify_user_id).first()
    auth_token = SpotifyAuthorisationToken(temp_user.refresh_token, temp_user.activated_at,
                                           temp_user.oauth_token)

    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    # Check if the playlist id is valid
    playlist_json = {}
    try:
        playlist_json = spotify.playlist(playlist_id, auth_token)
        playlist_json["duration"] = song_length
    except SpotifyError as e:
        if "Invalid playlist Id" in str(e):
            return abort(400, "The Playlist ID you passed is not valid")

    # Get the owner of the playlist
    playlist_json_owner = playlist_json["owner"]["id"]

    # Get the owner of the playlist
    spotify_user_object: SpotifyUser = SpotifyUser.query.filter(
        SpotifyUser.spotify_user_id == playlist_json_owner).first()

    # Check if the owner is in the spotify user database
    if not spotify_user_object:
        return abort(400, f"The user ({playlist_json_owner}) the playlist belongs to does not exist in the tool. \n"
                          f"You have to create it manually.")

    # Create the playlist and add it to the database
    database_playlist = Playlist(spotify_id=playlist_id, spotify_user=spotify_user_object.id, users=[],
                                 max_song_length=song_length)
    db.session.add(database_playlist)
    db.session.commit()
    return playlist_json
示例#9
0
def add_track_to_playlist():
    """
    Add tracks to the playlist
    :return: status 201, or 400
    """

    playlist_id: str = request.args.get('playlist-id')

    if not playlist_id:
        return abort(400, "You did not give a playlist-id")

    auth_token = get_token_by_playlist(playlist_id)

    if not auth_token:
        return abort(400, "No playlist with this id found")

    # Check if expired and update the user
    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    json = request.get_json()

    if "track-list" in json:
        track_list = json["track-list"]
    else:
        return abort(400, "Your request body has not track-list")

    track_list = check_songs(track_list, auth_token, playlist_id)

    if not track_list:
        return abort(400, "You passed an empty message")

    spotify.add_playlist_tracks(playlist_id, track_list, auth_token)
    return Response(status=201)
def get_token_by_playlist(playlist_id: str) -> SpotifyAuthorisationToken:
    """
    Takes the playlist id and gets the valid token for the playlist
    :param playlist_id: The id of the playlist
    :return: A valid and reauthorized token
    """

    playlist: Playlist = Playlist.query.filter(Playlist.spotify_id == playlist_id).first()
    if not playlist:
        return None

    spotify_user = SpotifyUser.query.filter(SpotifyUser.id == playlist.spotify_user).first()
    if not spotify_user:
        return None

    auth_token = SpotifyAuthorisationToken(refresh_token=spotify_user.refresh_token,
                                           authorisation_token=spotify_user.oauth_token,
                                           activation_time=spotify_user.activated_at)
    if auth_token.is_expired():
        auth_token = spotify.reauthorize(auth_token)
        user_id = spotify.me(auth_token)["id"]
        update_spotify_user(user_id, auth_token)

    return auth_token