-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·471 lines (389 loc) · 14 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
from waitress import serve
from flask import Flask, render_template, request, redirect, session, flash, send_file
from forms import AddLoginForm, AddSignUpForm, AddDelAccForm, AddSelectionForm, AddImportForm
from models import db, connect_db, User, Subscription, LikedVideo, Playlist, PlaylistVideo, Credential
from flask_bcrypt import Bcrypt
import datetime
import jwt
from functools import wraps
import os
import ytmapi
import json
import tempfile
app = Flask(__name__)
# Get secrets from environment
app.config["SECRET_KEY"] = os.environ['FLASK_KEY']
JWT_KEY = os.environ['JWT_KEY']
DATABASE_URL = os.environ['DATABASE_URL']
PORT = os.environ['PORT']
# App config
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
SESSION_COOKIE_SAMESITE = 'Strict'
bcrypt = Bcrypt()
connect_db(app)
db.create_all()
def get_session_user():
"""
Returns the username from the session as a string
"""
if app.config['TESTING'] == True:
return 'testuser'
# Check token for username
authtoken = session['auth']
authtoken = jwt.decode(authtoken, JWT_KEY)
username = authtoken['user']
return username
def get_user(username):
"""
Returns a user object
"""
user = User.query.filter_by(username=username).first_or_404()
return user
def create_login_token(username):
"""
Save login session to JWT token
"""
token = {
'user' : username,
'exp' : datetime.datetime.utcnow() + datetime.timedelta(days=14),
}
jwttoken = jwt.encode(token, JWT_KEY)
session['auth'] = jwttoken
return
def login_required(function):
@wraps(function)
def wrapper(*args, **kwargs):
"""
Checks if username in JWT token is correct or sends to login screen
"""
try:
username = get_session_user()
user = get_user(username)
if user.username == username:
return function()
else:
return redirect('/login')
except:
return redirect('/login')
return redirect('/login')
return wrapper
@app.route('/')
def mainpage():
return render_template('welcome.html')
@app.route('/learnmore')
def learnmore():
return render_template('learnmore.html')
@app.route('/privacy')
def privacyPolicy():
return render_template('privacy_policy.html')
@app.route('/login', methods=["GET", "POST"])
def login():
"""
Login page and form logic
"""
# Dictionary for potential login errors
errors = {
'username' : {
'error' : '',
'labelclass' : '',
'icon' : ''
},
'password' : {
'error' : '',
'labelclass' : '',
'icon' : ''
}
}
form = AddLoginForm()
# Check for CSRF
if form.validate_on_submit():
username = form.username.data
password = form.password.data
# User in database check
try:
user = get_user(username)
# Password correct check
if bcrypt.check_password_hash(user.password_hash, password):
# Provide user login token
create_login_token(username)
return redirect("/dashboard")
else:
errors['password']['error'] = 'Password is incorrect!'
errors['password']['labelclass'] = 'mdc-text-field--invalid'
errors['password']['icon'] = 'error'
except:
errors['username']['error'] = 'User does not exist!'
errors['username']['labelclass'] = 'mdc-text-field--invalid'
errors['username']['icon'] = 'error'
return render_template('login.html', form=form, errors=errors)
@app.route('/signup', methods=["GET", "POST"])
def signup():
"""
Sign-Up page and form logic
"""
# Template for potential login errors
errors = {
'username' : {
'error' : '',
'labelclass' : '',
'icon' : ''
},
}
# Check for CSRF
form = AddSignUpForm()
if form.validate_on_submit():
# Get form values
username = form.username.data
password = form.password.data
privacyAgree = form.privacyAgree.data
# Check if user already exists
try:
userExists = get_user(username)
if bool(userExists):
userExists = True
except:
userExists = False
# Error message for a missing user
if userExists:
errors['username']['error'] = 'User already exists!'
errors['username']['labelclass'] = 'mdc-text-field--invalid'
errors['username']['icon'] = 'error'
# Condition for valid input
if not userExists and privacyAgree:
# Hash password
hash = bcrypt.generate_password_hash(password)
hashutf = hash.decode("utf8")
# Save user to database
newuser = User(
username = username,
password_hash = hashutf
)
db.session.add(newuser)
db.session.commit()
# Generate login token
create_login_token(username)
return redirect("/dashboard")
return render_template('signup.html', form=form, errors=errors)
else:
return render_template('signup.html', form=form, errors=errors)
@app.route('/auth/google/signin')
@login_required
def authenticate():
"""
Redirects to OAuth 2.0 flow link
"""
# Generate authorization_url and state token
authorization_url = ytmapi.get_authorization_url()
# Save current state to user's session
session['state'] = authorization_url[1]
url = authorization_url[0]
return redirect(url)
@app.route('/auth/google/callback')
@login_required
def auth():
"""
OAuth 2.0 flow callback logic
"""
# Ensure that the request is not a forgery and that the user sending this connect request is the expected user.
if request.args.get('state', '') != session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Retreive auth code from query or return error
auth_code = request.args.get('code', '')
if auth_code == '':
response = make_response(json.dumps(request.args['error']), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Turn auth code into an access token
state = request.args['state']
# Grab user info
username = get_session_user()
user = get_user(username)
# Pass access token to api client
credentials = ytmapi.get_access_token(auth_code, state)
ytmapi.save_credentials(credentials, user)
return 'Account successfully linked. You may now close this window.'
@app.route('/dashboard')
@login_required
def dashboard():
"""
Main application interface
"""
# Grab user info
username = get_session_user()
user = get_user(username)
# Grab user's data
likeslist = LikedVideo.query.filter_by(user_id=user.id).all()
subslist = Subscription.query.filter_by(user_id=user.id).all()
playlistlist = Playlist.query.filter_by(user_id=user.id).all()
# Add forms
delAccForm = AddDelAccForm()
selectionForm = AddSelectionForm()
importForm = AddImportForm()
return render_template('dashboard.html', subs=subslist, likes=likeslist, playlists=playlistlist, delAccForm=delAccForm, selectionForm=selectionForm, importForm=importForm)
@app.route('/delacc', methods=["POST"])
@login_required
def delAcc():
"""
Form route for deleting user from database
"""
# Check for CSRF
delAccForm = AddDelAccForm()
if delAccForm.validate_on_submit():
# Grab user info
username = get_session_user()
user = get_user(username)
# Delete user from DB
db.session.delete(user)
db.session.commit()
return redirect("/")
@app.route('/delete', methods=["POST"])
@login_required
def deleteSelection():
"""
Form route for deleting selected data from database
"""
# Check for CSRF
selectionform = AddSelectionForm()
if selectionform.validate_on_submit():
# Grab user info
username = get_session_user()
user = get_user(username)
# Grab form data
items = request.form.to_dict()
try:
items.pop("csrf_token")
except:
pass
# Query items and delete from database
for item in items.keys():
if item[-7:] == 'videoid':
LikedVideo.query.filter_by(user_id=user.id).filter_by(video_id=item[:-7]).delete()
elif item[-7:] == 'channel':
Subscription.query.filter_by(user_id=user.id).filter_by(channel_id=item[:-7]).delete()
elif item[-7:] == 'playlis':
playlist = Playlist.query.filter_by(user_id=user.id).filter_by(resource_id=item[:-7]).first_or_404()
db.session.delete(playlist)
db.session.commit()
return redirect("/dashboard")
@app.route('/logout')
@login_required
def logout():
"""
Link to log out
"""
# Remove JWT login token
session.clear()
return redirect('/')
@app.route('/import', methods=["POST"])
@login_required
def importData():
"""
Form route for importing selected data
"""
# Check for CSRF
importForm = AddImportForm()
if importForm.validate_on_submit():
# Grab user info
username = get_session_user()
user = get_user(username)
# Run api client imports for selected categories
if importForm.subscriptions.data:
ytmapi.import_subscriptions(user)
if importForm.likedVideos.data:
ytmapi.import_liked_videos(user)
if importForm.playlists.data:
ytmapi.import_playlists(user)
return redirect('/dashboard')
@app.route("/download-json", methods=["POST"])
@login_required
def downloadJson():
"""
Form route to download selected data as a file
"""
# Check for CSRF
selectionform = AddSelectionForm()
if selectionform.validate_on_submit():
# Grab user info
username = get_session_user()
user = get_user(username)
# Grab form data
items = request.form.to_dict()
# Query items from form and put into dictionary
items.pop("csrf_token")
data = {
"liked_videos":[],
"subscriptions":[],
"playlists":[]
}
for item in items.keys():
if item[-7:] == 'videoid':
video = LikedVideo.query.filter_by(user_id=user.id).filter_by(video_id=item[:-7]).first_or_404()
videoDict = {
'channel_title' : video.channel_title,
'video_title' : video.title,
'video_id' : video.video_id
}
data['liked_videos'].append(videoDict)
elif item[-7:] == 'channel':
channel = Subscription.query.filter_by(user_id=user.id).filter_by(channel_id=item[:-7]).first_or_404()
channelDict = {
'channel_title' : channel.title,
'channel_id' : channel.channel_id
}
data['subscriptions'].append(channelDict)
elif item[-7:] == 'playlis':
playlist = Playlist.query.filter_by(user_id=user.id).filter_by(resource_id=item[:-7]).first_or_404()
playlist_items = PlaylistVideo.query.filter_by(playlist_id=playlist.id).all()
playlist_contents = list(map(lambda x: x.video_id, playlist_items))
playlistDict = {
'playlist_title' : playlist.title,
'privacy_status' : playlist.privacy_status,
'playlist_id' : playlist.resource_id,
'playlist_items' : playlist_contents
}
data['playlists'].append(playlistDict)
# Make tempfile and write dictionary as JSON
fd, filepath = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
json.dump(data, f)
return send_file(filepath, as_attachment=True, attachment_filename="Your_YouTube_Data.json")
@app.route("/export", methods=["POST"])
@login_required
def exportData():
"""
Form route to export selected data
"""
# Check for CSRF
selectionform = AddSelectionForm()
if selectionform.validate_on_submit():
# Grab user info
username = get_session_user()
user = get_user(username)
# Grab form data
items = request.form.to_dict()
items.pop("csrf_token")
# Query items from form and export using api client
for item in items.keys():
if item[-7:] == 'videoid':
video = LikedVideo.query.filter_by(user_id=user.id).filter_by(video_id=item[:-7]).first_or_404()
ytmapi.export_rating(video, user)
elif item[-7:] == 'channel':
channel = Subscription.query.filter_by(user_id=user.id).filter_by(channel_id=item[:-7]).first_or_404()
try:
ytmapi.export_subscription(channel, user)
except:
pass
elif item[-7:] == 'playlis':
playlist = Playlist.query.filter_by(user_id=user.id).filter_by(resource_id=item[:-7]).first_or_404()
response = ytmapi.export_playlist(playlist, user)
playlist_items = PlaylistVideo.query.filter_by(playlist_id=playlist.id).all()
playlist_contents = list(map(lambda x: x.video_id, playlist_items))
for videoId in playlist_contents:
ytmapi.export_playlist_vid(videoId, response['id'], user)
return redirect('/dashboard')
# Web Server
serve(app, port=PORT)