-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.py
1095 lines (987 loc) · 42.8 KB
/
db.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from contextlib import contextmanager
import os
import random
from flask import current_app, jsonify
import psycopg2
from psycopg2.pool import ThreadedConnectionPool
from psycopg2.extras import DictCursor, RealDictCursor
import math
pool = None
def setup():
global pool
DATABASE_URL = os.environ['DATABASE_URL']
current_app.logger.info(f"creating db connection pool")
pool = ThreadedConnectionPool(1, 100, dsn=DATABASE_URL, sslmode='require')
@contextmanager
def get_db_connection():
try:
connection = pool.getconn()
yield connection
finally:
pool.putconn(connection)
@contextmanager
def get_db_cursor(commit=False, useRealDict=False):
if useRealDict: factory = RealDictCursor
else: factory = DictCursor
with get_db_connection() as connection:
cursor = connection.cursor(cursor_factory=factory)
try:
yield cursor
if commit:
connection.commit()
finally:
cursor.close()
### *************************************************************************************
### *************************************************************************************
### ******************************GETTER / SELECT FUNCTIONS******************************
### *************************************************************************************
### *************************************************************************************
def get_playlist(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_playlists WHERE playlist_id=%s;", (playlist_id,))
return cursor.fetchall()
def get_playlist_songs_ids(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT song_id FROM mixtape_fm_playlist_songs WHERE playlist_id=%s;", (playlist_id,))
return cursor.fetchall()
def get_song_from_song_id(song_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_songs WHERE song_id=%s;", (song_id,))
return cursor.fetchone()
def get_playlist_songs(playlist_id):
playlist_songs_ids = get_playlist_songs_ids(playlist_id)
playlist_songs = []
for song_id_arr in playlist_songs_ids:
song_id = song_id_arr[0]
song_result = get_song_from_song_id(song_id)
# songs: [song_id:””, name:””, picture:”img”, artist:’’”, album:””, genre:””|null, duration:””|null]
duration = None
if (song_result[4]):
seconds = int(song_result[4]) % 60000
while (seconds >= 100):
seconds /= 10
duration = str(math.floor(int(song_result[4]) / 60000)) + ':' + str(int(seconds))
# print("duration= " + duration)
song = {'song_id': song_result[6], 'name': song_result[0], 'picture': song_result[5], 'artist': song_result[1], 'album': song_result[2], 'genre': song_result[3], 'duration': duration}
playlist_songs.append(song)
return playlist_songs
def get_user_playlists(user_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_playlists WHERE user_id=%s;", (user_id,))
return cursor.fetchall()
def get_playlist_id(user_id, playlist_name):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_id FROM mixtape_fm_playlists WHERE user_id=%s AND playlist_name=%s;", (user_id, playlist_name))
return cursor.fetchone()
def getPlaylistId(user_id, playlist_name):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_id FROM mixtape_fm_playlists WHERE user_id=%s AND playlist_name=%s;", (user_id, playlist_name))
return cursor.fetchone()
def get_playlist_song_id(playlist_id, song_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_song_id FROM mixtape_fm_playlist_songs WHERE playlist_id=%s AND song_id=%s;", (playlist_id, song_id))
return cursor.fetchone()
def getPlaylistSongId(playlist_id, song_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_song_id FROM mixtape_fm_playlist_songs WHERE playlist_id=%s AND song_id=%s;", (playlist_id, song_id))
return cursor.fetchone()
def get_song_id(name, artist, album, genre, duration, image):
with get_db_cursor(True) as cursor:
if (genre == None and image == None):
cursor.execute("SELECT song_id FROM mixtape_fm_songs WHERE name=%s AND artist=%s AND album=%s AND duration=%s;", \
(name, artist, album, duration))
elif (genre == None and image != None):
cursor.execute("SELECT song_id FROM mixtape_fm_songs WHERE name=%s AND artist=%s AND album=%s AND image=%s AND duration=%s;", \
(name, artist, album, image, duration))
elif (genre != None and image == None):
cursor.execute("SELECT song_id FROM mixtape_fm_songs WHERE name=%s AND artist=%s AND album=%s AND genre=%s AND duration=%s;", \
(name, artist, album, genre, duration))
else:
cursor.execute("SELECT song_id FROM mixtape_fm_songs WHERE name=%s AND artist=%s AND album=%s AND genre=%s AND image=%s AND duration=%s;", \
(name, artist, album, genre, image, duration))
return cursor.fetchone()
def get_comment(commenter_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_comments WHERE comment_user_id=%s AND playlist_id=%s;", (commenter_id, playlist_id))
return cursor.fetchall()
def get_tag_id_helper(tag_name):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT tag_id FROM mixtape_fm_tags WHERE tag_name=%s;", (tag_name,))
return cursor.fetchone()
def get_tag_id(tag_name):
tag_id = get_tag_id_helper(tag_name)
print('tag_id= ' + str(tag_id))
if (tag_id is None or tag_id == []):
insert_tag(tag_name)
tag_id = get_tag_id_helper(tag_name)
return tag_id[0]
def checkUser(user_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_users WHERE user_id=%s;", (str(user_id), ))
return cursor.fetchall()
def successfulLoginAttempt(user_id, user_display_name, image):
print("user_id= " + str(user_id))
if (user_id == None):
return False
checkVal = checkUser(user_id)
if (checkVal == []):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_users (user_id, user_display_name, image) VALUES (%s, %s, %s);", (str(user_id), str(user_display_name), str(image)))
return True
else:
return True
def playlist_search(variation, search_word):
with get_db_cursor(True) as cursor:
search_symbol = ''
if (variation == 1):
search_symbol = '%' + search_word + '%'
elif (variation == 2):
search_symbol = '% ' + search_word + '%'
elif (variation == 3):
search_symbol = '%' + search_word + ' %'
elif (variation == 4):
search_symbol = '% ' + search_word + ' %'
elif (variation == 5):
search_symbol = '% ' + search_word + '.%'
elif (variation == 6):
search_symbol = '%' + search_word + ',%'
elif (variation == 7):
search_symbol = search_word + '%'
elif (variation == 8):
search_symbol = '%' + search_word
else:
print("variation value %d invalid" % (variation))
return None
cursor.execute("SELECT * FROM mixtape_fm_playlists WHERE playlist_name ILIKE %s;", (search_symbol, ))
return cursor.fetchall()
def tag_id_search(variation, search_word):
with get_db_cursor(True) as cursor:
search_symbol = ''
if (variation == 1):
search_symbol = '%' + search_word + '%'
elif (variation == 2):
search_symbol = '% ' + search_word + '%'
elif (variation == 3):
search_symbol = '%' + search_word + ' %'
elif (variation == 4):
search_symbol = '% ' + search_word + ' %'
elif (variation == 5):
search_symbol = '% ' + search_word + '.%'
elif (variation == 6):
search_symbol = '%' + search_word + ',%'
elif (variation == 7):
search_symbol = search_word + '%'
elif (variation == 8):
search_symbol = '%' + search_word
else:
print("variation value %d invalid" % (variation))
return None
cursor.execute("SELECT tag_id FROM mixtape_fm_tags WHERE tag_name ILIKE %s;", (search_symbol, ))
return cursor.fetchall()
def get_playlist_id_from_tag_id(tag_id):
if (tag_id == None):
return None
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_id FROM mixtape_fm_playlist_tags WHERE tag_id = %s;", (tag_id, ))
return cursor.fetchone()
def get_playlist_from_playlist_id(playlist_id):
if (playlist_id == None):
return None
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_playlists WHERE playlist_id = %s;", (playlist_id, ))
return cursor.fetchone()
def get_playlists_from_tag_id_results(tag_id_results):
playlists = []
if (tag_id_results):
for tag_id_result in tag_id_results:
if (tag_id_result):
playlist_id = get_playlist_id_from_tag_id(tag_id_result[0])
if (playlist_id):
playlist = get_playlist_from_playlist_id(playlist_id[0])
if (playlist not in playlists):
playlists.append(playlist)
return get_playlists_from_results(playlists)
# TODO
# def get_if_saved(playlist_result):
# with get_db_cursor(True) as cursor:
# cursor.execute("SELECT * FROM mixtape_fm_playlists WHERE playlist_id")
# TODO
# def get_playlists_from_saved_results(playlist_results):
# saved_results = []
# if (playlist_results):
# for playlist_result in playlist_results:
# saved_result = get_if_saved(playlist_result)
# if (saved_result != None and saved_result != []):
# saved_results.append(saved_result)
# return get_playlists_from_results(saved_results)
def getSavedPlaylistsSearchOpt(user_id, variation, search_word):
if (user_id == None or user_id == ""):
return []
with get_db_cursor(True, useRealDict=True) as cursor:
search_symbol = ''
if (variation == 1):
search_symbol = '%' + search_word + '%'
elif (variation == 2):
search_symbol = '% ' + search_word + '%'
elif (variation == 3):
search_symbol = '%' + search_word + ' %'
elif (variation == 4):
search_symbol = '% ' + search_word + ' %'
elif (variation == 5):
search_symbol = '% ' + search_word + '.%'
elif (variation == 6):
search_symbol = '%' + search_word + ',%'
elif (variation == 7):
search_symbol = search_word + '%'
elif (variation == 8):
search_symbol = '%' + search_word
else:
print("variation value %d invalid" % (variation))
return None
cursor.execute(
"""SELECT pl.playlist_id,
pl.playlist_name AS name,
pl.image AS image,
COALESCE(AVG(r.stars), 0) AS rating,
ARRAY_REMOVE(ARRAY_AGG(t.tag_name), NULL) AS tags
FROM mixtape_fm_playlists_saved ps
LEFT JOIN mixtape_fm_playlists pl on ps.playlist_id = pl.playlist_id
LEFT JOIN mixtape_fm_playlist_tags pt ON pl.playlist_id = pt.playlist_id
LEFT JOIN mixtape_fm_tags t ON pt.tag_id = t.tag_id
LEFT JOIN mixtape_fm_ratings r ON r.playlist_id = pl.playlist_id
WHERE ps.user_id = %s AND pl.playlist_name ILIKE %s
GROUP BY pl.playlist_id, pl.playlist_name, pl.image;""", (user_id, search_symbol))
return changePlaylistDicts(cursor.fetchall())
# TODO: Create search keyword matching, using sql operators 'like' and 'ilike'
## Make a function compiling results from searching for songs in db and playlists, tags preferable
def search(user_id, search_word):
ret_dict = {}
ret_dict['name_results'] = []
ret_dict['tag_results'] = []
ret_dict['saved_results'] = []
print(search_word)
if (search_word == None or search_word == ''):
return ret_dict
playlist_results = []
tag_id_results = []
og_saved_results = []
for variation in range(1, 9):
playlist_results = playlist_results + playlist_search(variation, search_word)
tag_id_results = tag_id_results + tag_id_search(variation, search_word)
og_saved_results = og_saved_results + getSavedPlaylistsSearchOpt(user_id, variation, search_word)
saved_results = []
for saved_result in og_saved_results:
if saved_result not in saved_results:
saved_results.append(saved_result)
name_results = get_playlists_from_results(playlist_results)
tag_results = get_playlists_from_tag_id_results(tag_id_results)
ret_dict['name_results'] = name_results
ret_dict['tag_results'] = tag_results
ret_dict['saved_results'] = saved_results
return ret_dict
## HELPER FUNCTION TO GET TAGS FOR PLAYLSITS
def get_tag_ids_from_playlist_id(playlist_id):
if (playlist_id == None):
return []
with get_db_cursor(True) as cursor:
cursor.execute("SELECT tag_id FROM mixtape_fm_playlist_tags WHERE playlist_id = %s;", (playlist_id, ))
return cursor.fetchall()
## HELPER FUNCTION TO GET TAGS FOR PLAYLISTS
def get_tag_from_id(tag_id):
if (tag_id == None):
return []
with get_db_cursor(True) as cursor:
cursor.execute("SELECT tag_name FROM mixtape_fm_tags WHERE tag_id = %s;", (tag_id, ))
return cursor.fetchone()
## HELPER FUNCTION TO GET PLAYLISTS
def getRatingAvg(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT AVG(stars) FROM mixtape_fm_ratings WHERE playlist_id = %s;", (playlist_id, ))
return cursor.fetchone()
# HELPER FUNCTION TO GET PLAYLISTS
def getUserIdFromPlaylistId(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT user_id FROM mixtape_fm_playlists WHERE playlist_id = %s;", (playlist_id, ))
return cursor.fetchone()
## HELPER FUNCTION TO GET PLAYLISTS
def getUserFromUserId(user_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_users WHERE user_id = %s;", (user_id, ))
return cursor.fetchone()
## returns user info
def getUserFromPlaylistId(playlist_id):
user_id = getUserIdFromPlaylistId(playlist_id)
user = []
if (user_id):
user = getUserFromUserId(user_id[0])
return user
def getRatingsNoUser(playlist_id):
ratings = []
if (playlist_id == None):
return ratings
# return jsonify(ratings)
db_ratings = get_ratings_no_user(playlist_id)
ratings = get_ratings_from_db_ratings(db_ratings)
return ratings
# return jsonify(ratings)
def get_playlist_from_result(playlist_result):
playlist = {'playlistID': None, 'userID': None, 'image': None, 'name': None, 'ratingAvg': None, \
'numRatings': None, 'tags': None, 'userDisplayName': None}
if (playlist_result == [] or playlist_result == None):
return playlist
else:
ratings = getRatingsNoUser(playlist_result[0])
tag_ids = get_tag_ids_from_playlist_id(playlist_result[0])
user = getUserFromPlaylistId(playlist_result[0])
tags = []
for tag_id in tag_ids:
db_tag = get_tag_from_id(tag_id[0])
tags.append(db_tag[0])
db_ratingAvg = getRatingAvg(playlist_result[0])
ratingAvg = 0
if (db_ratingAvg[0]):
ratingAvg = str(round(float(db_ratingAvg[0]), 2))
playlist = {'playlistID': playlist_result[0], 'userID': user[0], 'image': playlist_result[4], 'name': playlist_result[2], 'ratingAvg': ratingAvg, \
'numRatings': len(ratings), 'tags': tags, 'userDisplayName': user[3]}
return playlist
## HELPER FUNCTION TO GET PLAYLISTS
def get_playlists_from_results(playlist_results):
playlists = []
for playlist in playlist_results:
# ratings = get_comments(playlist[0]) TODO
ratings = getRatingsNoUser(playlist[0])
tag_ids = get_tag_ids_from_playlist_id(playlist[0])
user = getUserFromPlaylistId(playlist[0])
tags = []
for tag_id in tag_ids:
db_tag = get_tag_from_id(tag_id[0])
tags.append(db_tag[0])
# tags = tags + get_tag_from_id(tag_id[0])
# Get average from ratings
db_ratingAvg = getRatingAvg(playlist[0])
ratingAvg = 0
if (db_ratingAvg[0]):
ratingAvg = (round(float(db_ratingAvg[0]), 2))
p_entry = {'playlistID': playlist[0], 'userID': user[0], 'image': playlist[4], 'name': playlist[2], 'ratingAvg': ratingAvg, \
'numRatings': len(ratings), 'tags': tags, 'userDisplayName': user[3]}
if (p_entry not in playlists):
playlists.append(p_entry)
# playlists.append({'playlistID': playlist[0], 'userID': user[0], 'image': playlist[4], 'name': playlist[2], 'ratingAvg': ratingAvg, \
# 'numRatings': len(ratings), 'tags': tags, 'userDisplayName': user[3]})
return playlists
# Takes user_id, returns array with {name, image, ratings, tags[], playlist_id}
def getPlaylists(user_id):
if (user_id == None):
return []
playlist_results = get_user_playlists(user_id)
playlists = get_playlists_from_results(playlist_results)
return playlists
# return jsonify(playlists)
def get_top_playlist_ids():
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_id FROM mixtape_fm_ratings ORDER BY stars DESC LIMIT 10;")
return cursor.fetchall()
def get_top_playlists():
playlist_ids = get_top_playlist_ids()
playlist_results = []
for playlist_id in playlist_ids:
playlist_result = get_playlist_from_playlist_id(playlist_id)
playlist_results.append(playlist_result[0])
# playlist_results.append(get_playlist_from_playlist_id(playlist_id))
return playlist_results
## Get 10 top rated playlists across the site
def getTopRatedPlaylists():
playlist_results = get_top_playlists()
playlists = get_playlists_from_results(playlist_results)
return playlists
# return jsonify(playlists)
def get_random_playlists(n):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_playlists ORDER BY random() LIMIT %s;", (n, ))
return cursor.fetchall()
## Gets n random playlists, returns array with {name, image, ratings, tags[], playlist_id}
def getRandomPlaylists(n):
if (n == None or n <= 0):
return []
# playlist_results = get_user_playlists(user_id)
playlist_results = get_random_playlists(n)
playlists = get_playlists_from_results(playlist_results)
return playlists
# playlists = get_playlists_from_results(playlist_results)
# if (len(playlists) < n):
# return playlists
# # return jsonify(playlists)
# else:
# random_playlists = random.sample(playlists, n)
# return random_playlists
# # return jsonify(random_playlists)
def isPlaylistRecent(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_user_recent_playlists WHERE user_id = %s AND playlist_id = %s;", (user_id, playlist_id))
return cursor.fetchall()
def updatePlaylistRecent(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("UPDATE mixtape_fm_user_recent_playlists SET timestamp = CURRENT_TIMESTAMP WHERE user_id = %s AND playlist_id = %s;", \
(user_id, playlist_id))
return
def playlistLeastRecent(user_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_user_recent_playlists WHERE user_id = %s ORDER BY timestamp ASC;", (user_id, ))
return cursor.fetchone()
def retrieveRecentPlaylists():
with get_db_cursor(True) as cursor:
cursor.execute("SELECT playlist_id FROM mixtape_fm_user_recent_playlists;")
return cursor.fetchall()
def getRecentPlaylists(n):
recent_playlist_ids = retrieveRecentPlaylists()
if (len(recent_playlist_ids) > n):
recent_playlist_ids = recent_playlist_ids[0:n+1]
db_playlists = []
for playlist_id in recent_playlist_ids:
db_playlist = get_playlist_from_playlist_id(playlist_id)
db_playlists.append(db_playlist[0])
# db_playlists.append(get_playlist_from_playlist_id(playlist_id))
playlists = get_playlists_from_results(db_playlists)
return playlists
# return jsonify(playlists)
def getUserPlaylists(user_id):
if (user_id == None or user_id == ""):
return []
# return jsonify([])
db_playlists = get_user_playlists(user_id)
print("getUserPlaylists")
print(db_playlists)
if (db_playlists == []):
return []
# return jsonify([])
playlists = get_playlists_from_results(db_playlists)
return playlists
# return jsonify(playlists)
## HELPER TO RETRIEVE COMMENTS
def get_comments(playlist_id):
if (playlist_id == None):
return []
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_comments WHERE playlist_id = %s;", (playlist_id, ))
# cursor.execute("SELECT * FROM mixtape_fm_comments WHERE playlist_id = %s ORDER BY stars DESC;", (playlist_id, ))
return cursor.fetchall()
def format_db_comments(db_comments):
comments = []
for comment in db_comments:
commenter_id = comment[1]
commenter = getUserFromUserId(commenter_id)
commenter_text = comment[3]
comments.append({'commenterID': commenter_id, 'commenterPFP': commenter[5], 'commentText': commenter_text})
return comments
def getComments(playlist_id):
if (playlist_id == None or playlist_id == ''):
return []
# return jsonify([])
db_comments = get_comments(playlist_id)
comments = format_db_comments(db_comments)
print("comments= " + str(comments))
return comments
# return jsonify(comments)
def get_rating(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_ratings WHERE rating_user_id=%s AND playlist_id=%s;", (user_id, playlist_id))
return cursor.fetchone()
def get_ratings_no_user(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_ratings WHERE playlist_id=%s;", (playlist_id, ))
return cursor.fetchall()
def get_all_ratings(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_ratings WHERE playlist_id=%s;", (playlist_id, ))
return cursor.fetchall()
def get_ratings_from_db_ratings(db_ratings):
ratings = []
if (db_ratings):
for db_rating in db_ratings:
user = getUserFromUserId(db_rating[1])
rating = {'raterID':user[0], 'raterPFP':user[5], 'rating':db_rating[3]}
ratings.append(rating)
return ratings
# def getRatings(playlist_id):
# ratings = []
# if (playlist_id == None):
# return ratings
# # return jsonify(ratings)
# db_ratings = get_ratings(playlist_id)
# ratings = get_ratings_from_db_ratings(db_ratings)
# return ratings
# # return jsonify(ratings)
def getRatings(user_id, playlist_id):
ratings = []
if (playlist_id == None or user_id == None):
return ratings
# return jsonify(ratings)
db_ratings = get_rating(user_id, playlist_id)
ratings = get_ratings_from_db_ratings(db_ratings)
return ratings
# return jsonify(ratings)
def getAllRatings(playlist_id):
ratings = []
if (playlist_id == None):
return ratings
# return jsonify(ratings)
db_ratings = get_all_ratings(playlist_id)
ratings = get_ratings_from_db_ratings(db_ratings)
return ratings
# return jsonify(ratings)
### *************************************************************************************
### *************************************************************************************
### ******************************SETTER / INSERT FUNCTIONS******************************
### *************************************************************************************
### *************************************************************************************
def insert_playlist(user_id, playlist_name, image):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_playlists (user_id, playlist_name, creation_date, image) VALUES (%s, %s, CURRENT_TIMESTAMP, %s);", \
(user_id, playlist_name, image))
playlist_id = get_playlist_id(user_id, playlist_name)
return playlist_id[0]
def insert_song_into_playlist(playlist_id, song_id, position):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_playlist_songs (playlist_id, song_id, position) VALUES (%s, %s, %s);", (playlist_id, song_id, position))
p_s_id = get_playlist_song_id(playlist_id, song_id)
return p_s_id[0]
def insert_song(name, artist, album, genre, duration, image):
if (name == None or artist == None or album == None or duration == None):
print("Invalid parameters:")
print(" name= " + str(name))
print(" artist= " + str(artist))
print(" album= " + str(album))
print(" duration= " + str(duration))
return None
if (get_song_id(name, artist, album, genre, duration, image) == None):
with get_db_cursor(True) as cursor:
if (genre == None and image != None):
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, duration, image) VALUES (%s, %s, %s, %s, %s);", \
(name, artist, album, duration, image))
elif (genre != None and image == None):
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, genre, duration) VALUES (%s, %s, %s, %s, %s);", \
(name, artist, album, genre, duration))
elif (genre == None and image == None):
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, duration) VALUES (%s, %s, %s, %s);", \
(name, artist, album, duration))
else:
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, genre, duration, image) VALUES (%s, %s, %s, %s, %s, %s);", \
(name, artist, album, genre, duration, image))
s_id = get_song_id(name, artist, album, genre, duration)
return s_id[0]
def insertSong(name, artist, album, genre, duration, image):
if (name == None or artist == None or album == None or duration == None):
print("Invalid parameters:")
print(" name= " + str(name))
print(" artist= " + str(artist))
print(" album= " + str(album))
print(" duration= " + str(duration))
return None
if (get_song_id(name, artist, album, genre, duration, image) == None):
with get_db_cursor(True) as cursor:
if (genre == None and image != None):
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, duration, image) VALUES (%s, %s, %s, %s, %s);", \
(name, artist, album, duration, image))
elif (genre != None and image == None):
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, genre, duration) VALUES (%s, %s, %s, %s, %s);", \
(name, artist, album, genre, duration))
elif (genre == None and image == None):
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, duration) VALUES (%s, %s, %s, %s);", \
(name, artist, album, duration))
else:
cursor.execute("INSERT INTO mixtape_fm_songs (name, artist, album, genre, duration, image) VALUES (%s, %s, %s, %s, %s, %s);", \
(name, artist, album, genre, duration, image))
s_id = get_song_id(name, artist, album, genre, duration, image)
return s_id[0]
def insertSongs(songs):
# FUTURE: break this into chunks?
if (songs is None or len(songs) <= 0): return
with get_db_cursor(True) as cursor:
values_str = ",".join([
cursor.mogrify(
"(%s,%s,%s,%s,%s,%s,%s)",
(song.get("id"),
song.get("name"),
song.get("artist"),
song.get("album"),
song.get("duration"),
nullIfNone(song.get("genre")),
nullIfNone(song.get("image")))
).decode('utf-8')
for song in songs
])
cursor.execute("INSERT INTO mixtape_fm_songs (song_id, name, artist, album, duration, genre, image) VALUES"
+ values_str
+ "ON CONFLICT (song_id) DO NOTHING")
# + " ON CONFLICT (song_id) DO UPDATE SET name = excluded.name, artist = excluded.artist,"
# + "album = excluded.album, duration = excluded.duration, genre = excluded.genre, image = excluded.image")
return
# each entry in songs contains: name, artist, album, duration
def insertSongsToPlaylist(playlist_id, song_ids):
print([i for i,_ in enumerate(song_ids)])
with get_db_cursor(True) as cursor:
value_str = ",".join([
cursor.mogrify(
"(%s,%s,%s)",
(playlist_id, song_id, i))
.decode('utf-8')
for i, song_id in enumerate(song_ids)
])
cursor.execute("INSERT INTO mixtape_fm_playlist_songs (playlist_id, song_id, position) VALUES"
+ value_str
+ " ON CONFLICT (playlist_id, position) DO NOTHING"); # unique constraint on this combo of columns
return
# def insert_new_user(user_id):
# with get_db_cursor(True) as cursor:
# cursor.execute("INSERT INTO mixtape_fm_users (user_id, spotify_linked) VALUES (%s, %s);", (user_id, 'FALSE'))
# return
# def insertNewComment(commenter_id, playlist_id, stars, content):
# # if (stars < 1 or stars > 5):
# # print("Invalid number of stars in review")
# # return None
# if (get_comment(commenter_id, playlist_id) != []):
# print("User has already left a review of this playlist")
# return None
# with get_db_cursor(True) as cursor:
# if (stars == '' and content != ''):
# cursor.execute("INSERT INTO mixtape_fm_comments (comment_user_id, playlist_id, content, timestamp) VALUES (%s, %s, %s, CURRENT_TIMESTAMP);", \
# (commenter_id, playlist_id, content))
# elif (content == '' and stars != ''):
# cursor.execute("INSERT INTO mixtape_fm_comments (comment_user_id, playlist_id, stars, timestamp) VALUES (%s, %s, %s, CURRENT_TIMESTAMP);", \
# (commenter_id, playlist_id, stars))
# else:
# cursor.execute("INSERT INTO mixtape_fm_comments (comment_user_id, playlist_id, stars, content, timestamp) VALUES (%s, %s, %s, %s, CURRENT_TIMESTAMP);", \
# (commenter_id, playlist_id, stars, content))
# return get_comment(commenter_id, playlist_id)
def insert_tag(tag_name):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_tags (tag_name) VALUES (%s);", (tag_name,))
return
def insert_playlist_tag_id(playlist_id, tag_id):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_playlist_tags (playlist_id, tag_id) VALUES (%s, %s);", (playlist_id, tag_id))
return
# def insert_playlist_tag(playlist_id, tag_name):
# tag_id = get_tag_id(tag_name)
# if (tag_id is None):
# tag_id = insert_tag(tag_name)
# insert_playlist_tag_id(playlist_id, tag_id)
# return
def removePlaylistLeastRecent(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_user_recent_playlists WHERE user_id = %s AND playlist_id = %s;", (user_id, playlist_id))
return
def deletePlaylistRecent(user_id):
least_recent = playlistLeastRecent(user_id)
removePlaylistLeastRecent(least_recent[0], least_recent[1])
return
def addPlaylistToRecent(user_id, playlist_id):
if (isPlaylistRecent(user_id, playlist_id) == []):
if (getNumPlaylistRecents(user_id) > 10):
deletePlaylistRecent(user_id)
insertPlaylistRecent(user_id, playlist_id)
else:
updatePlaylistRecent(user_id, playlist_id)
return
def check_ratings(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_ratings WHERE rating_user_id=%s AND playlist_id=%s;", (user_id, playlist_id))
return cursor.fetchall()
def updateRatings(user_id, playlist_id, rating, updating=False):
with get_db_cursor(True) as cursor:
if (updating):
cursor.execute("UPDATE mixtape_fm_ratings SET stars=%s WHERE rating_user_id=%s AND playlist_id=%s;", \
(rating, user_id, playlist_id))
else:
cursor.execute("INSERT INTO mixtape_fm_ratings (rating_user_id, playlist_id, stars, timestamp) VALUES (%s, %s, %s, CURRENT_TIMESTAMP);", \
(user_id, playlist_id, rating))
return
def ratePlaylist(user_id, playlist_id, rating):
if (user_id == None or playlist_id == None or rating == None):
print("Invalid parameters:")
print(" user_id= " + str(user_id))
print(" playlist_id= " + str(playlist_id))
print(" rating= " + str(rating))
return
if (rating < 1 or rating > 5):
print("Invalid rating of " + str(rating) + " stars")
return
if (check_ratings(user_id, playlist_id) != []):
updateRatings(user_id, playlist_id, rating, True)
else:
updateRatings(user_id, playlist_id, rating, False)
return
def insert_comment(user_id, playlist_id, comment):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_comments (comment_user_id, playlist_id, content, timestamp) VALUES (%s, %s, %s, CURRENT_TIMESTAMP);", \
(user_id, playlist_id, comment))
return
def addComment(user_id, playlist_id, comment):
if (user_id == None or playlist_id == None or comment == None):
print("Invalid parameters:")
print(" user_id= " + str(user_id))
print(" playlist_id= " + str(playlist_id))
print(" comment= " + str(comment))
return
insert_comment(user_id, playlist_id, comment)
return
def deleteRating(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_ratings WHERE rating_user_id=%s AND playlist_id=%s;", \
(user_id, playlist_id))
return
def deleteComment(user_id, playlist_id, comment):
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_comments WHERE comment_user_id=%s AND playlist_id=%s AND content=%s;", \
(user_id, playlist_id, comment))
return
def deleteComments(user_id, playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_comments WHERE comment_user_id=%s AND playlist_id=%s;", \
(user_id, playlist_id))
return
def create_playlist(user_id, playlist_name, image):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_playlists (user_id, playlist_name, creation_date, image) VALUES (%s, %s, CURRENT_TIMESTAMP, %s);",
(user_id, playlist_name, image))
return
def createPlaylist(user_id, playlist_name, image, song_ids):
if (user_id == None or playlist_name == None):
print("Invalid parameters")
print(" user_id= " + str(user_id))
print(" playlist_name= " + str(playlist_name))
return None
if (check_playlists(user_id, playlist_name) != []):
print("Playlist already exists for user_id= %s, playlist_name= %s" % (user_id, playlist_name))
return None
create_playlist(user_id, playlist_name, image)
p_id = get_playlist_id(user_id, playlist_name)
playlist_id = p_id[0]
position = 0
for song_id in song_ids:
insert_song_into_playlist(playlist_id, song_id, position)
position += 1
return playlist_id
def delete_song(playlist_id, song_id):
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_playlist_songs WHERE playlist_id=%s AND song_id=%s;", \
(playlist_id, song_id))
return
def deleteSongs(user_id, playlist_id, song_ids):
if (user_id == None or playlist_id == None or song_ids == []):
print("Invalid parameters")
print(" user_id= " + str(user_id))
print(" playlist_id= " + str(playlist_id))
print(" song_ids= " + str(song_ids))
return None
for song_id in song_ids:
if (song_id != None):
delete_song(playlist_id, song_id)
return playlist_id
def delete_playlist_songs(playlist_id):
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_playlist_songs WHERE playlist_id=%s;", (playlist_id, ))
return
def update_playlist(user_id, playlist_id, playlist_name, playlist_image=None):
with get_db_cursor(True) as cursor:
if (playlist_image == None):
cursor.execute("UPDATE mixtape_fm_playlists SET playlist_name=%s WHERE user_id=%s AND playlist_id=%s;", \
(playlist_name, user_id, playlist_id))
else:
cursor.execute("UPDATE mixtape_fm_playlists SET playlist_name=%s, image=%s WHERE user_id=%s AND playlist_id=%s;", \
(playlist_name, playlist_image, user_id, playlist_id))
return
# def updatePlaylist(user_id, playlist_id, added_song_ids, deleted_song_ids, playlist_name, playlist_image):
def updatePlaylist(user_id, playlist_id, song_ids, playlist_name, playlist_image):
if (user_id == None or playlist_id == None or playlist_name == None or song_ids == []):
print("Invalid parameters")
print(" user_id= " + str(user_id))
print(" playlist_id= " + str(playlist_id))
print(" playlist_name= " + str(playlist_name))
print(" song_ids= " + str(song_ids))
return None
delete_playlist_songs(playlist_id)
if (playlist_image == None):
update_playlist(user_id, playlist_id, playlist_name)
else:
update_playlist(user_id, playlist_id, playlist_name, playlist_image)
# position = 0
print(song_ids)
insertSongsToPlaylist(playlist_id, song_ids)
# for song_id in song_ids:
# insert_song_into_playlist(playlist_id, song_id, position)
# position += 1
return playlist_id
def check_if_tagged_helper(playlist_id, tag_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_playlist_tags WHERE playlist_id=%s AND tag_id=%s;", (playlist_id, tag_id))
return cursor.fetchone()
def playlist_is_tagged(playlist_id, tag_id):
if (check_if_tagged_helper(playlist_id, tag_id) != []):
return True
else:
return False
def add_tag(tag_name):
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_tags (tag_name) VALUES (%s);", (tag_name, ))
return
def addTag(tag_name):
if (tag_name == None):
print("Invalid tag_name= " + str(tag_name))
return None
if (check_tag_exists(tag_name) != []):
return get_tag_id(tag_name)
else:
add_tag(tag_name)
return get_tag_id(tag_name)
# POST savePlaylist(userID, playlistID): so we can keep track of the user’s saved playlists
def savePlaylist(user_id, playlist_id):
if (user_id == None or playlist_id == None):
print("Invalid parameters:")
print(" user_id= " + str(user_id))
print(" playlist_id= " + str(playlist_id))
return
with get_db_cursor(True) as cursor:
cursor.execute("INSERT INTO mixtape_fm_playlists_saved (playlist_id, user_id) VALUES (%s, %s);", (playlist_id, user_id))
return
def get_saved_playlist_ids(user_id):
with get_db_cursor(True) as cursor:
cursor.execute("SELECT * FROM mixtape_fm_playlists_saved WHERE user_id = %s;", (user_id, ))
return cursor.fetchall()
def getSavedPlaylists(user_id):
if (user_id == None):
print("Invalid parameter:")
print(" user_id= " + str(user_id))
return
playlist_ids = get_saved_playlist_ids(user_id)
playlist_results = []
for playlist_id in playlist_ids:
playlist_results.append(get_playlist_from_playlist_id(playlist_id[0]))
playlists = get_playlists_from_results(playlist_results)
return playlists
# return jsonify(playlists)
def unsavePlaylist(user_id, playlist_id):
if (user_id == None or playlist_id == None):
print("Invalid parameters:")
print(" user_id= " + str(user_id))
print(" playlist_id= " + str(playlist_id))
return
with get_db_cursor(True) as cursor:
cursor.execute("DELETE FROM mixtape_fm_playlists_saved WHERE playlist_id=%s AND user_id=%s;", (playlist_id, user_id))
return
def getRandomPlaylistsOpt(n):
with get_db_cursor(True, useRealDict=True) as cursor:
cursor.execute(
"""SELECT pl.playlist_id,
pl.playlist_name AS name,
pl.image AS image,
COALESCE(AVG(r.stars), 0) AS rating,
ARRAY_REMOVE(ARRAY_AGG(t.tag_name), NULL) AS tags
FROM mixtape_fm_playlists pl
LEFT JOIN mixtape_fm_playlist_tags pt ON pl.playlist_id = pt.playlist_id
LEFT JOIN mixtape_fm_tags t ON pt.tag_id = t.tag_id
LEFT JOIN mixtape_fm_ratings r ON r.playlist_id = pl.playlist_id
GROUP BY pl.playlist_id, pl.playlist_name, pl.image
ORDER BY RANDOM()
LIMIT %s""", (n,))
return changePlaylistDicts(cursor.fetchall())
def getUserPlaylistsOpt(user_id):
if (user_id == None or user_id == ""):
return []
with get_db_cursor(True, useRealDict=True) as cursor:
cursor.execute(
"""SELECT pl.playlist_id,
pl.playlist_name AS name,
pl.image AS image,
COALESCE(AVG(r.stars), 0) AS rating,
ARRAY_REMOVE(ARRAY_AGG(t.tag_name), NULL) AS tags
FROM mixtape_fm_playlists pl
LEFT JOIN mixtape_fm_playlist_tags pt ON pl.playlist_id = pt.playlist_id