This repository has been archived by the owner on Mar 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
176 lines (139 loc) · 5.1 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import os
import json
from furl import furl
import requests
from flask import Flask
from flask import session
from flask import redirect, request
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, current_user, login_user
def get_env_variable(name):
try:
return os.environ[name]
except KeyError:
message = "Expected environment variable '{}' not set.".format(name)
raise Exception(message)
# get env vars OR ELSE
POSTGRES_URL = get_env_variable("POSTGRES_URL") # 5432
POSTGRES_USER = get_env_variable("POSTGRES_USER")
POSTGRES_PW = get_env_variable("POSTGRES_PW")
POSTGRES_DB = get_env_variable("POSTGRES_DB")
REDIS_URL = get_env_variable("REDIS_URL") # 6379
SPOTIFY_CLIENT_ID = get_env_variable("SPOTIFY_CLIENT_ID")
SPOTIFY_CLIENT_SECRET = get_env_variable("SPOTIFY_CLIENT_SECRET")
SPOTIFY_REDIRECT_URL = get_env_variable("SPOTIFY_REDIRECT_URL")
SPOTIFY_SCOPES = "user-read-private user-read-email user-read-playback-state user-read-currently-playing"
app = Flask(__name__)
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = REDIS_URL
app.secret_key = get_env_variable("SECRET_KEY")
DB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(user=POSTGRES_USER,pw=POSTGRES_PW,url=POSTGRES_URL,db=POSTGRES_DB)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning
db = SQLAlchemy(app)
login_manager = LoginManager(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
spotify_id = db.Column(db.String(200), unique=False, nullable=True)
spotify_token = db.Column(db.String(200), unique=False, nullable=True)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self.spotify_id
@login_manager.user_loader
def load_user(user_id):
return User.query.filter_by(spotify_id=user_id).first()
@app.cli.command('resetdb')
def resetdb_command():
"""Destroys and creates the database + tables."""
from sqlalchemy_utils import database_exists, create_database, drop_database
if database_exists(DB_URL):
print('Deleting database.')
drop_database(DB_URL)
if not database_exists(DB_URL):
print('Creating database.')
create_database(DB_URL)
#db.drop_all()
print('Creating tables.')
db.create_all()
print('Shiny!')
def go_to_spotify():
# https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow
data = {
"client_id": SPOTIFY_CLIENT_ID,
"response_type": "code",
"redirect_uri": SPOTIFY_REDIRECT_URL,
#"state": ,
"scope": SPOTIFY_SCOPES,
}
url = "https://accounts.spotify.com/authorize"
redirect_url = furl(url)
redirect_url.args = data
return redirect(redirect_url.url)
@app.route("/")
def start():
if not current_user.is_authenticated:
# redirect to spotify login
return go_to_spotify()
d = get_data(current_user.spotify_token)
return render_template("main.html", **d)
@app.route("/current")
def current():
d = get_data(current_user.spotify_token)
return json.dumps(d)
def get_data(spotify_token):
url = "https://api.spotify.com/v1/me/player/currently-playing"
headers = {'Authorization': "Bearer {}".format(spotify_token)}
r = requests.get(url, headers=headers)
parsed = json.loads(r.text)
img_src = parsed["item"]["album"]["images"][0]["url"]
return {
"img_src": img_src,
"artists": list(map(lambda x: {"name": x["name"]}, parsed["item"]["artists"])),
"album_name": parsed["item"]["album"]["name"],
"track_name": parsed["item"]["name"],
"track_ms_total": parsed["item"]["duration_ms"],
"track_ms_progress": parsed["progress_ms"],
"track_is_playing": parsed["is_playing"],
"track_uri": parsed["item"]["uri"],
}
@app.route("/callback")
def login_callback():
code = request.args.get('code')
error = request.args.get('error')
state = request.args.get('state')
#TODO: handle error cases?
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": SPOTIFY_REDIRECT_URL,
"client_id": SPOTIFY_CLIENT_ID,
"client_secret": SPOTIFY_CLIENT_SECRET,
}
url = "https://accounts.spotify.com/api/token"
r = requests.post(url, data=data)
parsed = json.loads(r.text)
token = parsed["access_token"]
#get spotify user id
url = "https://api.spotify.com/v1/me"
headers = {'Authorization': "Bearer {}".format(token)}
r = requests.get(url, headers=headers)
parsed = json.loads(r.text)
spotify_id = parsed["id"]
user = User.query.filter_by(spotify_id=spotify_id).first()
if not user is None:
user.spotify_token = token
else:
user = User(spotify_id=spotify_id, spotify_token=token)
db.session.add(user)
db.session.commit()
login_user(user)
return redirect("/")
if __name__ == "__main__":
app.debug = True
app.run()