SocialNetwork
96 строк · 3.2 Кб
1import os2import uuid3
4import spotipy5from flask import session, request, redirect6from flask_login import current_user7
8from data import db_session9from data.users import User10
11caches_folder = './.spotify_caches/'12if not os.path.exists(caches_folder):13os.makedirs(caches_folder)14
15SCOPE = 'user-top-read user-read-playback-position user-read-private user-read-email ' \16'playlist-read-private user-library-read user-library-modify playlist-read-collaborative ' \17'playlist-modify-public playlist-modify-private ugc-image-upload user-follow-read ' \18'user-follow-modify user-read-playback-state user-modify-playback-state ' \19'user-read-currently-playing user-read-recently-played streaming'20
21
22def session_cache_path():23return caches_folder + session.get('uuid')24
25
26def spotify_login_required(func):27def wrapper(**kwargs):28if not session.get('uuid'):29# Step 1. Visitor is unknown, give random ID30session['uuid'] = str(uuid.uuid4())31
32cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path=session_cache_path())33auth_manager = spotipy.oauth2.SpotifyOAuth(34scope=SCOPE,35cache_handler=cache_handler,36show_dialog=True)37
38db_sess = db_session.create_session()39user = db_sess.query(User).get(current_user.id)40
41if request.args.get("code"):42# Step 3. Being redirected from Spotify auth page43token = request.args.get("code")44auth_manager.get_access_token(token)45return redirect('/music')46
47if not auth_manager.validate_token(cache_handler.get_cached_token()):48# Step 2. Display sign in link when no token49auth_url = auth_manager.get_authorize_url()50return redirect(auth_url)51
52# Step 4. Signed in, display data53spotify = spotipy.Spotify(auth_manager=auth_manager)54
55if not user.spotify_id or user.spotify_id != spotify.current_user()['id']:56user.spotify_id = spotify.current_user()['id']57db_sess.commit()58
59return func(**kwargs, spotify=spotify)60
61wrapper.__name__ = func.__name__62return wrapper63
64
65def get_followed_artists(spotify: spotipy.Spotify):66artists = spotify.current_user_followed_artists(limit=50)['artists']['items']67all_artists = artists68while artists:69artists = \70spotify.current_user_followed_artists(limit=50, after=all_artists[-1]['id'])['artists'][71'items']72all_artists += artists73
74return all_artists75
76
77def get_all_artist_tracks(artist_id: str, spotify: spotipy.Spotify):78loop = 079albums = spotify.artist_albums(artist_id, limit=50, album_type='album')['items']80all_albums = albums81
82while albums:83loop += 184albums = spotify.artist_albums(artist_id, limit=50, offset=50, album_type='album')['items']85all_albums += albums86
87loop = 088singles = spotify.artist_albums(artist_id, limit=50, album_type='single')['items']89all_singles = singles90
91while singles:92loop += 193singles = spotify.artist_albums(artist_id, limit=50, offset=50, album_type='single')['items']94all_singles += albums95
96return {'albums': all_albums, 'singles': all_singles}97