-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.py
92 lines (76 loc) · 2.58 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/python3
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from flask import Flask, url_for, session, request, redirect
import json
import time
import pandas as pd
from .downloadvideos import DownloadVideosFromTitles
# App config
app = Flask(__name__)
app.secret_key = 'SOMETHING-RANDOM'
app.config['SESSION_COOKIE_NAME'] = 'spotify-login-session'
@app.route('/')
def login():
sp_oauth = create_spotify_oauth()
auth_url = sp_oauth.get_authorize_url()
print(auth_url)
return redirect(auth_url)
@app.route('/authorize')
def authorize():
sp_oauth = create_spotify_oauth()
session.clear()
code = request.args.get('code')
token_info = sp_oauth.get_access_token(code)
session["token_info"] = token_info
return redirect("/getTracks")
@app.route('/logout')
def logout():
for key in list(session.keys()):
session.pop(key)
return redirect('/')
@app.route('/getTracks')
def get_all_tracks():
session['token_info'], authorized = get_token()
session.modified = True
if not authorized:
return redirect('/')
sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))
results = []
iter = 0
while True:
offset = iter * 50
iter += 1
curGroup = sp.current_user_saved_tracks(limit=50, offset=offset)['items']
for idx, item in enumerate(curGroup):
track = item['track']
val = track['name'] + " - " + track['artists'][0]['name']
results += [val]
if (len(curGroup) < 50):
break
df = pd.DataFrame(results, columns=["song names"])
df.to_csv('songs.csv', index=False)
return "done"
# Checks to see if token is valid and gets a new token if not
def get_token():
token_valid = False
token_info = session.get("token_info", {})
# Checking if the session already has a token stored
if not (session.get('token_info', False)):
token_valid = False
return token_info, token_valid
# Checking if token has expired
now = int(time.time())
is_token_expired = session.get('token_info').get('expires_at') - now < 60
# Refreshing token if it has expired
if (is_token_expired):
sp_oauth = create_spotify_oauth()
token_info = sp_oauth.refresh_access_token(session.get('token_info').get('refresh_token'))
token_valid = True
return token_info, token_valid
def create_spotify_oauth():
return SpotifyOAuth(
client_id="id",
client_secret="secret",
redirect_uri=url_for('authorize', _external=True),
scope="user-library-read")