SocialNetwork

Форк
0
/
spotify.py 
96 строк · 3.2 Кб
1
import os
2
import uuid
3

4
import spotipy
5
from flask import session, request, redirect
6
from flask_login import current_user
7

8
from data import db_session
9
from data.users import User
10

11
caches_folder = './.spotify_caches/'
12
if not os.path.exists(caches_folder):
13
    os.makedirs(caches_folder)
14

15
SCOPE = '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

22
def session_cache_path():
23
    return caches_folder + session.get('uuid')
24

25

26
def spotify_login_required(func):
27
    def wrapper(**kwargs):
28
        if not session.get('uuid'):
29
            # Step 1. Visitor is unknown, give random ID
30
            session['uuid'] = str(uuid.uuid4())
31

32
        cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path=session_cache_path())
33
        auth_manager = spotipy.oauth2.SpotifyOAuth(
34
            scope=SCOPE,
35
            cache_handler=cache_handler,
36
            show_dialog=True)
37

38
        db_sess = db_session.create_session()
39
        user = db_sess.query(User).get(current_user.id)
40

41
        if request.args.get("code"):
42
            # Step 3. Being redirected from Spotify auth page
43
            token = request.args.get("code")
44
            auth_manager.get_access_token(token)
45
            return redirect('/music')
46

47
        if not auth_manager.validate_token(cache_handler.get_cached_token()):
48
            # Step 2. Display sign in link when no token
49
            auth_url = auth_manager.get_authorize_url()
50
            return redirect(auth_url)
51

52
        # Step 4. Signed in, display data
53
        spotify = spotipy.Spotify(auth_manager=auth_manager)
54

55
        if not user.spotify_id or user.spotify_id != spotify.current_user()['id']:
56
            user.spotify_id = spotify.current_user()['id']
57
            db_sess.commit()
58

59
        return func(**kwargs, spotify=spotify)
60

61
    wrapper.__name__ = func.__name__
62
    return wrapper
63

64

65
def get_followed_artists(spotify: spotipy.Spotify):
66
    artists = spotify.current_user_followed_artists(limit=50)['artists']['items']
67
    all_artists = artists
68
    while artists:
69
        artists = \
70
            spotify.current_user_followed_artists(limit=50, after=all_artists[-1]['id'])['artists'][
71
                'items']
72
        all_artists += artists
73

74
    return all_artists
75

76

77
def get_all_artist_tracks(artist_id: str, spotify: spotipy.Spotify):
78
    loop = 0
79
    albums = spotify.artist_albums(artist_id, limit=50, album_type='album')['items']
80
    all_albums = albums
81

82
    while albums:
83
        loop += 1
84
        albums = spotify.artist_albums(artist_id, limit=50, offset=50, album_type='album')['items']
85
        all_albums += albums
86

87
    loop = 0
88
    singles = spotify.artist_albums(artist_id, limit=50, album_type='single')['items']
89
    all_singles = singles
90

91
    while singles:
92
        loop += 1
93
        singles = spotify.artist_albums(artist_id, limit=50, offset=50, album_type='single')['items']
94
        all_singles += albums
95

96
    return {'albums': all_albums, 'singles': all_singles}
97

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.