-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
475 lines (319 loc) · 12.9 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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import os
import psycopg2
from flask import Flask,abort, request, redirect, render_template , flash, redirect, session, g
from sqlalchemy.exc import IntegrityError
from werkzeug.exceptions import HTTPException
from models import db, connect_db, User , Community , Post , Song , Playlist , UserCommu , Likes
from form import UserAddForm , LoginForm , PostForm , ProfileForm
from api import headers
import requests
SEARCH_URL = "https://api.spotify.com/v1"
CURR_USER_KEY = "curr_user"
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL',"postgresql:///spotify" )
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'chlwjdals492wjddbs')
connect_db(app)
##############################################################################
# User signup/login/logout
@app.before_request
def add_user_to_g():
"""If we're logged in, add curr user to Flask global."""
if CURR_USER_KEY in session:
g.user = User.query.get(session[CURR_USER_KEY])
else:
g.user = None
def do_login(user):
"""Log in user."""
session[CURR_USER_KEY] = user.id
def do_logout():
"""Logout user."""
if CURR_USER_KEY in session:
del session[CURR_USER_KEY]
@app.route('/signup' , methods=["GET","POST"])
def register_user():
"""Handle user singup.
Create new user and add to DB. Redirect to home page"""
form = UserAddForm()
if form.validate_on_submit():
try:
user = User.signup (
username = form.username.data,
password = form.password.data,
email = form.email.data,
image_url = form.image_url.data or '/static/images/default-pic.png',
)
db.session.commit()
except IntegrityError:
flash("Username already taken", 'danger')
return render_template('signup.html', form=form)
do_login(user)
return redirect ('/')
else:
return render_template('user/signup.html' , form=form)
@app.route('/login' , methods=["GET", "POST"])
def login_user():
"""Handle user login"""
form = LoginForm()
if form.validate_on_submit():
user = User.authenticate(
form.username.data ,
form.password.data)
if user:
do_login(user)
flash(f"Hello, {user.username}!", "success")
return redirect("/")
flash("Invalid credentials.", 'danger')
return render_template('user/login.html', form=form)
@app.route('/logout')
def logout():
"""Handle logout of user."""
# IMPLEMENT THIS
session.pop(CURR_USER_KEY)
flash('You have successfully logged out', 'danger')
return redirect('/login')
##############################################################################
# Community
@app.route('/community')
def join_community():
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/login")
else:
community = Community.query.all()
return render_template('community/index.html', community = community)
@app.route('/community/<int:com_id>', methods=['GET','POST'])
def one_community(com_id):
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/login")
else:
community = Community.query.get_or_404(com_id)
posts = (Post.query.order_by(Post.id.desc()).all())
user = g.user
songs = Song.query.all()
if request.method == "POST":
commu = UserCommu(
user_id = request.form.get('user_id'),
commu_id = request.form.get('commu_id')
)
db.session.add(commu)
db.session.commit()
usercommu = UserCommu.query.all()
all_commu = Community.query.all()
return render_template('/community/first_page.html',all_commu=all_commu , community=community , posts=posts, user=user, likes=user.likes, usercommu=usercommu, songs=songs)
@app.route('/community/<int:com_id>/user/<int:user_id>/delete', methods=['GET','POST'])
def unjoin_community(user_id, com_id):
"""Delete a post"""
user = User.query.get_or_404(user_id)
commu = Community.query.get_or_404(com_id)
user_comm = UserCommu.query.filter(UserCommu.user_id == user.id , UserCommu.commu_id == commu.id).first()
db.session.delete(user_comm)
db.session.commit()
return redirect(f"/community/{commu.id}")
##############################################################################
# Show a list of users
@app.route('/community/<int:com_id>/users')
def show_all_users(com_id):
commu = Community.query.get_or_404(com_id)
users = commu.users
return render_template('/user/list_users.html', commu=commu , users=users)
##############################################################################
# Handle posts (Users can upload , edit and delete posts)
@app.route('/community/<int:commu_id>/posts/add' , methods=["GET", "POST"] )
def add_post(commu_id):
"""add post"""
form = PostForm()
user_id = session[CURR_USER_KEY]
songs = [(s.id , s.title ) for s in Song.query.filter(Song.user_id == user_id).all() ]
form.song_id.choices = songs
commu = Community.query.get_or_404(commu_id)
if form.validate_on_submit():
title = form.title.data
content = form.content.data
song_id = form.song_id.data
commu_id = commu.id
new_post = Post(title=title , content=content ,song_id=song_id, commu_id=commu_id ,user_id=user_id)
db.session.add(new_post)
db.session.commit()
return redirect(f"/community/{commu_id}")
else:
return render_template('/post/add.html', form=form , commu=commu)
@app.route('/posts/<int:post_id>/edit' , methods=["GET", "POST"])
def edit_post(post_id):
post =Post.query.get_or_404(post_id)
form = PostForm(obj=post)
user_id = session[CURR_USER_KEY]
songs = [(s.id , s.title) for s in Song.query.filter(Song.user_id == user_id).all() ]
form.song_id.choices = songs
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
return redirect(f"/community/{post.commu_id}")
else:
return render_template('/post/edit.html', form=form , post=post)
@app.route('/posts/<int:post_id>/community/<int:com_id>/delete', methods=["GET","POST"])
def delete_post(post_id, com_id):
"""Delete a post"""
post = Post.query.get_or_404(post_id)
commu = Community.query.get_or_404(com_id)
db.session.delete(post)
db.session.commit()
return redirect(f'/community/{commu.id}')
##############################################################################
# Search Song
@app.route('/search', methods=['GET','POST'])
def search_song():
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/login")
else:
q = request.args.get('artist')
params = {
"q": q,
"type": "track",
"limit": "10"
}
res = requests.get(f'{SEARCH_URL}/search', params=params, headers=headers)
data = res.json()
tracks = data["tracks"]["items"]
user = session[CURR_USER_KEY]
if request.method == "POST":
song = Song(
images = request.form.get('track_image'),
title = request.form.get('track_title'),
artist = request.form.get('track_artist'),
link = request.form.get('track_link'),
user_id = session[CURR_USER_KEY]
)
db.session.add(song)
db.session.commit()
playlist = Playlist(
song_id = song.id,
user_id = session[CURR_USER_KEY]
)
db.session.add(playlist)
db.session.commit()
return render_template('user/search.html', tracks=tracks , user=user , q=q)
##############################################################################
# Show user page (profile , posts , communities)
@app.route('/users/<int:user_id>')
def show_user_profile(user_id):
"""Show user's profile"""
user = User.query.get_or_404(user_id)
return render_template('/user/show_profile.html', user=user)
@app.route('/users/<int:user_id>/posts')
def show_user_post(user_id):
"""Show user's posts"""
user = User.query.get_or_404(user_id)
return render_template('/user/show_post.html', user=user)
@app.route('/users/<int:user_id>/communities')
def show_communities(user_id):
"""Show user's communities"""
user = User.query.get_or_404(user_id)
communities = user.communities
return render_template('/user/show_community.html', user=user , communities=communities)
##############################################################################
# Show playlist // users can delete song on their playlist
@app.route('/users/<int:user_id>/playlist')
def show_playlist(user_id):
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
user = User.query.get_or_404(user_id)
return render_template('user/playlist.html', user=user , songs=user.songs )
@app.route('/users/<int:user_id>/playlist/<int:song_id>/delete', methods=["GET","POST"])
def delete_song(user_id, song_id):
"""Delete a song"""
user = User.query.get_or_404(user_id)
song = Song.query.get_or_404(song_id)
db.session.delete(song)
db.session.commit()
return redirect(f"/users/{user.id}/playlist")
##############################################################################
# LIKE
@app.route('/users/<int:user_id>/likes', methods=["GET"])
def show_likes(user_id):
"""Show user's liked posts"""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
user = User.query.get_or_404(user_id)
songs = Song.query.all()
likes = user.likes
return render_template('user/likes.html', user=user , songs=songs , likes=likes)
@app.route('/posts/<int:post_id>/likes', methods=['POST'])
def add_like(post_id):
"""Toggle a liked post for the currently-logged-in user."""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
liked_post = Post.query.get_or_404(post_id)
if liked_post.user_id == g.user.id:
return abort(403)
user_likes = g.user.likes
if liked_post in user_likes:
g.user.likes = [like for like in user_likes if like != liked_post]
else:
g.user.likes.append(liked_post)
db.session.commit()
return redirect(f"/community/{liked_post.communities.id}")
##############################################################################
# Handle user profile
@app.route('/users/<int:user_id>/profile', methods=['GET','POST'])
def edit_user_profile(user_id):
"""Edit user's profile"""
user = User.query.get_or_404(user_id)
form = ProfileForm()
if form.validate_on_submit():
user.username = form.username.data,
user.password = form.password.data,
user.image_url = form.image_url.data or '/static/images/default-pic.png',
user.email = form.email.data
db.session.commit()
return redirect(f"/users/{user.id}")
else:
return render_template('user/edit_profile.html', form=form)
@app.route('/users/<int:user_id>/delete', methods=["GET","POST"])
def delete_user(user_id):
"""Delete user."""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return redirect("/signup")
##############################################################################
# Homepage Error
#
# https://flask.palletsprojects.com/en/2.0.x/errorhandling/
@app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
# now you're handling non-HTTP exceptions only
return render_template("500.html", e=e), 500
##############################################################################
# Homepage
@app.route('/')
def homepage():
"""render homepage"""
return render_template('home_none.html')
##############################################################################
# Turn off all caching in Flask
# (useful for dev; in production, this kind of stuff is typically
# handled elsewhere)
#
# https://stackoverflow.com/questions/34066804/disabling-caching-in-flask
@app.after_request
def add_header(req):
"""Add non-caching headers on every request."""
req.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
req.headers["Pragma"] = "no-cache"
req.headers["Expires"] = "0"
req.headers['Cache-Control'] = 'public, max-age=0'
return req