This repository has been archived by the owner on Jan 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.py
3065 lines (2807 loc) · 128 KB
/
application.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
import hashlib
import os
import random
import shutil
import urllib
import uuid
import zipfile
from re import findall
from time import time
from urllib.parse import urlparse, urljoin
import flask_admin as admin
import pytz
import simplejson as json
from PIL import Image as PILImage
from flask import Flask, abort, jsonify, render_template, send_file, Response, request, session, \
flash, url_for, redirect, g
from flask_babel import Babel
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, login_user, logout_user, \
current_user, login_required
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, desc, Numeric, String, event, exc, or_
from sqlalchemy.pool import Pool
from sqlalchemy.sql import text, func
from tornado.ioloop import IOLoop
from tornado.web import Application, FallbackHandler
from tornado.websocket import WebSocketHandler
from tornado.wsgi import WSGIContainer
from werkzeug.datastructures import Headers
from factories.artistFactory import ArtistFactory
from factories.releaseFactory import ReleaseFactory
from flask_session import Session as FlaskSession
from importers.collectionImporter import CollectionImporter
from resources.artistListApi import ArtistListApi
from resources.artistApi import ArtistApi
from resources.releaseApi import ReleaseApi
from resources.common import *
from resources.genreListApi import GenreListApi
from resources.id3 import ID3
from resources.jinjaFilters import format_tracktime, format_timedelta, calculate_release_tracks_Length, \
group_release_tracks_filepaths, format_age_from_date, calculate_release_discs, count_new_lines, \
format_datetime_for_user, get_user_track_rating
from resources.labelListApi import LabelListApi
from resources.logger import Logger
from resources.m3u import M3U
from resources.models.Artist import Artist
from resources.models.Collection import Collection
from resources.models.Genre import Genre
from resources.models.Image import Image
from resources.models.Label import Label
from resources.models.Playlist import Playlist
from resources.models.PlaylistTrack import PlaylistTrack
from resources.models.Release import Release
from resources.models.ReleaseLabel import ReleaseLabel
from resources.models.ReleaseMedia import ReleaseMedia
from resources.models.Track import Track
from resources.models.User import User
from resources.models.UserArtist import UserArtist
from resources.models.UserRelease import UserRelease
from resources.models.UserRole import UserRole
from resources.models.UserTrack import UserTrack
from resources.nocache import nocache
from resources.playlistTrackListApi import PlaylistTrackListApi
from resources.processingBase import ProcessorBase
from resources.processor import Processor
from resources.releaseListApi import ReleaseListApi
from resources.playHistoryApi import PlayHistoryApi
from resources.scanner import Scanner
from resources.trackListApi import TrackListApi
from resources.trackApi import TrackApi
from resources.userListApi import UserListApi
from resources.userArtistListApi import UserArtistListApi
from resources.userReleaseListApi import UserReleaseListApi
from resources.userTracklistApi import UserTrackListApi
from resources.userApi import UserApi
from searchEngines.imageSearcher import ImageSearcher
from viewModels.RoadieModelView import RoadieModelView, RoadieModelAdminRequiredView
from viewModels.RoadieUserArtistModelView import RoadieUserArtistModelView
from viewModels.RoadieUserReleaseModelView import RoadieUserReleaseModelView
from viewModels.RoadieUserTrackModelView import RoadieUserTrackModelView
clients = []
logger = Logger()
avatarSize = 30, 30
userCache = dict()
app = Flask(__name__)
app.jinja_env.filters['format_tracktime'] = format_tracktime
app.jinja_env.filters['format_timedelta'] = format_timedelta
app.jinja_env.filters['calculate_release_tracks_Length'] = calculate_release_tracks_Length
app.jinja_env.filters['group_release_tracks_filepaths'] = group_release_tracks_filepaths
app.jinja_env.filters['format_age_from_date'] = format_age_from_date
app.jinja_env.filters['calculate_release_discs'] = calculate_release_discs
app.jinja_env.filters['count_new_lines'] = count_new_lines
app.jinja_env.filters['format_datetime_for_user'] = format_datetime_for_user
app.jinja_env.filters['get_user_track_rating'] = get_user_track_rating
with open(os.path.join(app.root_path, "settings.json"), "r") as rf:
config = json.load(rf)
if not config:
raise RuntimeError("Invalid Configuration")
app.config.update(config)
trackPathReplace = None
if 'ROADIE_TRACK_PATH_REPLACE' in config:
trackPathReplace = config['ROADIE_TRACK_PATH_REPLACE']
thumbnailSize = config['ROADIE_THUMBNAILS']['Height'], config['ROADIE_THUMBNAILS']['Width']
siteName = config['ROADIE_SITE_NAME']
app.config['SQLALCHEMY_DATABASE_URI'] = config['ROADIE_DATABASE_URL']
sa = SQLAlchemy(app)
dbSession = sa.session()
conn = sa.engine
flask_bcrypt = Bcrypt(app)
bcrypt = Bcrypt()
api = Api(app)
babel = Babel(app)
FlaskSession(app)
ALLOWED_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
NEW_ID = "__new__"
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = str(uuid.uuid4())
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except:
dbapi_connection._pool.dispose()
# raise DisconnectionError - pool will try
# connecting again up to three times before raising.
raise exc.DisconnectionError()
cursor.close()
@app.before_request
def before_request():
g.siteName = siteName
g.user = current_user
@app.teardown_request
def shutdown_session(exception=None):
try:
dbSession.remove()
if exception and dbSession.is_active:
dbSession.rollback()
logger.exception("Shutdown Session")
except:
pass
def getUser(userId=None):
"""
Cache the user to reduce DB hits
:param userId: str
:rtype : User
:return: Return user for Current logged in user cache enabled
"""
userId = userId or getUserId()
if userId not in userCache:
userCache[userId] = dbSession.query(User).filter(User.roadieId == userId).first()
return userCache[userId]
def getUserId():
"""
Return the UserId for the Curent user
:return: str
"""
return current_user.roadieId
def getArtist(artistId):
"""
Abstract the fetch artist from DB and include any UserArtist
:param artistId: str
:return: Artist
"""
return dbSession.query(Artist) \
.filter(Artist.roadieId == artistId) \
.first()
def getRelease(releaseId):
"""
Abstract the fetch release from DB and include any UserRelease
:param releaseId: str
:return: Release
"""
return dbSession.query(Release) \
.filter(Release.roadieId == releaseId) \
.first()
def getTrack(trackId):
"""
Abstract the fetch Track from DB and include any UserTrack
:param trackId: str
:return: Track
"""
return dbSession.query(Track) \
.filter(Track.roadieId == trackId) \
.first()
def getUserArtistRating(artistId):
user = getUser()
userArtist = dbSession.query(UserArtist) \
.filter(UserArtist.userId == user.id) \
.filter(UserArtist.artistId == artistId).first()
if not userArtist:
userArtist = UserArtist()
userArtist.rating = 0
userArtist.roadieId = str(uuid.uuid4())
userArtist.userId = user.id
userArtist.artistId = artistId
dbSession.add(userArtist)
return userArtist
def getUserReleaseRating(releaseId):
user = getUser()
userRelease = dbSession.query(UserRelease) \
.filter(UserRelease.userId == user.id) \
.filter(UserRelease.releaseId == releaseId).first()
if not userRelease:
userRelease = UserRelease()
userRelease.rating = 0
userRelease.roadieId = str(uuid.uuid4())
userRelease.releaseId = releaseId
userRelease.userId = user.id
dbSession.add(userRelease)
return userRelease
def pathToTrack(track):
"""
Adjust the path to a track with any OS or config substitutions
:param track: Track
:return: str
"""
try:
path = os.path.join(config["ROADIE_LIBRARY_FOLDER"], track.filePath, track.fileName)
if trackPathReplace:
for rpl in trackPathReplace:
for key, val in rpl.items():
path = path.replace(key, val)
return path
except:
pass
return None
@app.route('/')
@login_required
def index():
lastPlayedInfos = []
for ut in dbSession.query(UserTrack).join(Track, Track.id == UserTrack.trackId).order_by(
desc(UserTrack.lastPlayed)).limit(50):
artistThumbnail = "/images/artist/thumbnail/"
if ut.track.artist:
artistThumbnail += str(ut.track.artist.roadieId)
else:
artistThumbnail += str(ut.track.releasemedia.release.artist.roadieId)
lastPlayedInfos.append({
'TrackId': str(ut.track.roadieId),
'TrackTitle': ut.track.title,
'ReleaseId': str(ut.track.releasemedia.release.roadieId),
'ReleaseTitle': ut.track.releasemedia.release.title,
'ReleaseThumbnail': "/images/release/thumbnail/" + str(ut.track.releasemedia.release.roadieId),
'ArtistId': str(ut.track.releasemedia.release.artist.roadieId) if not ut.track.artist else str(
ut.track.artist.roadieId),
'ArtistName': ut.track.releasemedia.release.artist.name if not ut.track.artist else ut.track.artist.name,
'ArtistThumbnail': artistThumbnail,
'UserId': str(ut.user.roadieId),
'Username': ut.user.username,
'UserThumbnail': "/images/user/avatar/" + str(ut.user.roadieId),
'UserRating': ut.rating,
'LastPlayed': arrow.get(ut.lastPlayed).humanize()
})
wsRoot = request.url_root.replace("http://", "ws://")
releases = []
for r in dbSession.query(Release).order_by(func.random()).limit(12):
if r and r.artist:
releases.append({
'id': r.roadieId,
'ArtistName': r.artist.name,
'Title': r.title,
'UserRating': 0
})
return render_template('home.html',
lastPlayedInfos=lastPlayedInfos,
wsRoot=wsRoot,
releases=releases)
@app.route("/release/setReleaseDate/<roadieId>/<new_release_date>/<set_tracks_year>", methods=['POST'])
def setReleaseDate(roadieId, new_release_date, set_tracks_year):
try:
setReleaseYearRelease = getRelease(roadieId)
user = getUser()
now = arrow.utcnow().datetime
if not setReleaseYearRelease or not user or not new_release_date:
return jsonify(message="ERROR")
setReleaseYearRelease.releaseDate = parseDate(new_release_date)
setReleaseYearRelease.lastUpdated = now
dbSession.commit()
if set_tracks_year == "true":
for media in setReleaseYearRelease.media:
for track in media.tracks:
trackPath = pathToTrack(track)
id3 = ID3(trackPath, config)
id3.updateFromRelease(setReleaseYearRelease, track)
# Update Database with folders found in Library as folder structure is bound to release year
processor = Processor(config, conn, dbSession, False, True)
releaseFolder = processor.albumFolder(setReleaseYearRelease.artist,
setReleaseYearRelease.releaseDate.strftime('%Y'),
setReleaseYearRelease.title)
processor.process(folder=releaseFolder, isReleaseFolder=True)
return jsonify(message="OK")
except:
logger.exception("Error In Set Release Date")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/release/setTitle/<roadieId>", methods=['POST'])
def setReleaseTitle(roadieId):
try:
setReleaseTitleRelease = getRelease(roadieId)
user = getUser()
now = arrow.utcnow().datetime
new_title = urllib.parse.unquote(request.form['tracksToMove'])
create_alternate_name = request.form['doCreateAlternateName']
set_tracks_title = request.form['doSetTracksTitle']
if not setReleaseTitleRelease or not user or not new_title:
return jsonify(message="ERROR")
oldTitle = setReleaseTitleRelease.title
setReleaseTitleRelease.title = new_title
if create_alternate_name == "true":
oldAlternateTitles = []
if setReleaseTitleRelease.alternateNames:
oldAlternateTitles = setReleaseTitleRelease.alternateNames
if oldTitle not in oldAlternateTitles:
oldAlternateTitles.append(oldTitle.replace("'", "''"))
# I cannot get setting the release alternateNames working so I did this direct update
t = text("UPDATE `release` SET alternateNames = '" + "|".join(oldAlternateTitles) + "' WHERE id = " + str(
setReleaseTitleRelease.id) + ";")
conn.execute(t)
setReleaseTitleRelease.lastUpdated = now
dbSession.commit()
if set_tracks_title == "true":
for media in setReleaseTitleRelease.media:
for track in media.tracks:
trackPath = pathToTrack(track)
try:
id3 = ID3(trackPath, config)
id3.updateFromRelease(setReleaseTitleRelease, track)
except:
logger.exception("Error in SetReleaseTitle Updating MP3 [" + track.roadieId + "]")
pass
return jsonify(message="OK")
except:
logger.exception("Error In Set Release Title")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/mergereleases/<release_roadie_id_to_merge>/<release_roadie_id_to_merge_into>/<add_as_media>",
methods=['POST'])
def mergeReleases(release_roadie_id_to_merge, release_roadie_id_to_merge_into, add_as_media):
try:
if not release_roadie_id_to_merge or not release_roadie_id_to_merge_into:
return jsonify(message="ERROR")
releaseToMerge = dbSession.query(Release).filter(Release.roadieId == release_roadie_id_to_merge).first()
releaseToMergeInto = dbSession.query(Release).filter(
Release.roadieId == release_roadie_id_to_merge_into).first()
if not releaseToMerge or not releaseToMergeInto:
return jsonify(message="ERROR")
if add_as_media == "True":
now = arrow.utcnow().datetime
mediaNumber = releaseToMergeInto.mediaCount
for media in releaseToMerge.media:
mediaNumber += 1
media.releaseId = releaseToMergeInto.id
media.releaseMediaNumber = mediaNumber
media.lastUpdated = now
releaseToMergeInto.mediaCount += 1
releaseToMergeInto.trackCount += media.trackCount
releaseToMerge.genres = []
dbSession.commit()
dbSession.delete(releaseToMerge)
dbSession.commit()
else:
return jsonify(message="ERROR")
return jsonify(message="OK")
except:
logger.exception("Error In Release Random")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/release/random/<count>", methods=['POST'])
def randomRelease(count):
try:
releases = []
for r in dbSession.query(Release).order_by(func.random()).limit(count):
releases.append({
'id': r.roadieId,
'ArtistName': r.artist.name,
'Title': r.title,
'UserRating': 0
})
return jsonify(message="OK", releases=releases)
except:
logger.exception("Error In Release Random")
return jsonify(message="ERROR")
@app.route("/browseArtists")
@login_required
def browseArtists():
return render_template('browseArtists.html')
@app.route("/browseReleases")
@login_required
def browseReleases():
return render_template('browseReleases.html')
@app.route("/randomizer/<random_type>")
@login_required
def randomizer(random_type):
user = getUser()
if random_type == "artist":
artist = dbSession.query(Artist).order_by(func.random()).first()
return playArtist(artist.roadieId, "0")
elif random_type == "release":
randomizerRelease = dbSession.query(Release).order_by(func.random()).first()
return playRelease(randomizerRelease.roadieId)
elif random_type == "tracksrandom" or random_type == "tracksrated":
sql = None
if random_type == "tracksrandom":
sql = ("SELECT t.*, r.roadieId AS releaseRoadieId, r.title AS releaseTitle,"
"rm.releaseMediaNumber AS releaseMediaNumber, r.releaseDate AS releaseDate, "
"ta.roadieId AS trackArtistRoadieId, ta.name AS trackArtistName, a.id AS artistId, "
"a.roadieId AS artistRoadieId, a.name AS artistName, rm.releaseMediaNumber "
"FROM `track` t "
"JOIN `releasemedia` rm ON (rm.id = t.releaseMediaId) "
"JOIN `release` r ON (r.id = rm.releaseId) "
"JOIN `artist` a ON (a.id = r.artistId) "
"LEFT JOIN `artist` ta ON (ta.id = t.artistId) "
"LEFT JOIN `userrelease` ur ON (ur.releaseId= r.id AND ur.userId = " + str(user.id) +
") LEFT JOIN `userartist` ua ON (ua.artistId = r.artistId AND ua.userId = " + str(user.id) +
") WHERE (RAND()<(SELECT ((1/COUNT(*))*100) FROM `track`)) "
"AND (HASH IS NOT NULL) AND ((ur.id IS NULL OR ur.isDisliked = 0) "
"AND (ua.id IS NULL OR ua.isDisliked = 0)) "
"ORDER BY RAND() "
"LIMIT 100;")
elif random_type == "tracksrated":
sql = ("SELECT t.*, r.roadieId AS releaseRoadieId, r.title AS releaseTitle, "
"rm.releaseMediaNumber AS releaseMediaNumber, r.releaseDate AS releaseDate, "
"ta.roadieId AS trackArtistRoadieId, ta.name AS trackArtistName, a.id AS artistId, "
"a.roadieId AS artistRoadieId, a.name AS artistName, rm.releaseMediaNumber "
"FROM `track` t "
"JOIN `releasemedia` rm ON (rm.id = t.releaseMediaId) "
"JOIN `release` r ON (r.id = rm.releaseId) "
"JOIN `artist` a ON (a.id = r.artistId) "
"LEFT JOIN `artist` ta ON (ta.id = t.artistId) "
"LEFT JOIN `userrelease` ur ON (ur.releaseId= r.id AND ur.userId = " + str(user.id) +
") LEFT JOIN `userartist` ua ON (ua.artistId = r.artistId AND ua.userId = " + str(user.id) +
") JOIN `usertrack` ut ON (ut.trackId = t.id AND ut.userId = " + str(user.id) +
") WHERE (RAND()<(SELECT ((1/COUNT(*))*100000) FROM `track`)) "
"AND (HASH IS NOT NULL) AND ((ur.id IS NULL OR ur.isDisliked = 0) "
"AND (ua.id IS NULL OR ua.isDisliked = 0) "
"AND (ut.rating > 0)) "
"ORDER BY RAND() "
"LIMIT 100;")
tracks = []
t = text(sql)
for trackRow in conn.execute(t):
track = Track()
track.id = trackRow.id
track.roadieId = trackRow.roadieId
track.duration = trackRow.duration
track.title = trackRow.title
track.trackNumber = trackRow.trackNumber
track.rating = trackRow.rating
track.playedCount = trackRow.playedCount
if track.artistId:
track = Release()
track.artist = Artist()
track.artist.id = trackRow.artistId
track.artist.roadieId = trackRow.trackArtistRoadieId
track.artist.name = trackRow.trackArtistName
release = Release()
release.roadieId = trackRow.releaseRoadieId
release.artist = Artist()
release.artist.id = trackRow.artistId
release.artist.roadieId = trackRow.artistRoadieId
release.artist.name = trackRow.artistName
release.title = trackRow.releaseTitle
release.releaseDate = trackRow.releaseDate
track.releasemedia = ReleaseMedia()
track.releasemedia.releaseMediaNumber = trackRow.releaseMediaNumber
t = M3U.makeTrackInfo(user, release, track)
if t:
tracks.append(t)
if user.doUseHtmlPlayer:
session['tracks'] = tracks
return player()
return send_file(M3U.generate(tracks),
as_attachment=True,
attachment_filename="playlist.m3u")
@app.route('/label/<label_id>')
@login_required
def labelDetail(label_id):
label = dbSession.query(Label).filter(Label.roadieId == label_id).first()
if not label:
return render_template('404.html'), 404
labelSummaries = conn.execute(text(
"SELECT ac.artistCount, r.releaseCount, rm.releaseMediaCount, ts.trackCount, ts.duration, ts.size " +
" FROM `label` l " +
" INNER JOIN " +
" ( " +
" select rl.labelId as labelId, count(rm.id) as releaseMediaCount " +
" From `releasemedia` rm " +
" join `release` r on rm.releaseId = r.id " +
" join `releaselabel` rl on rl.releaseId = r.id " +
" group by rl.labelId " +
" ) as rm ON rm.labelId = l.id " +
" INNER JOIN " +
" ( " +
" select rl.labelId as labelId, count(r.id) as releaseCount " +
" from `release` r " +
" join `releaselabel` rl on rl.releaseId = r.id " +
" group by rl.labelId " +
" ) as r ON r.labelId = l.id " +
" INNER JOIN " +
" ( " +
" SELECT rl.labelId as labelId, COUNT(1) AS trackCount, " +
" SUM(t.duration) AS duration, SUM(t.fileSize) AS size " +
" FROM `track` t " +
" JOIN `releasemedia` rm ON rm.id = t.releaseMediaId " +
" JOIN `release` r ON r.id = rm.releaseId " +
" join `releaselabel` rl on rl.releaseId = r.id " +
" WHERE t.fileName IS NOT NULL " +
" GROUP BY rl.labelId " +
" ) AS ts ON ts.labelId = l.id " +
" INNER JOIN " +
" ( " +
" select rl.labelId as labelId, count(DISTINCT r.artistId) as artistCount " +
" from `release` r " +
" join `releaselabel` rl on rl.releaseId = r.id " +
" group by rl.labelId " +
" ) as ac ON ac.labelId = l.id " +
" WHERE l.roadieId = '" + label_id + "';", autocommit=True)
.columns(artistCount=Integer,
releaseCount=Integer,
releaseMediaCount=Integer,
trackCount=Integer,
releaseTrackTime=Integer,
releaseTrackFileSize=Integer,
)) \
.fetchone()
counts = {'artists': labelSummaries[0] if labelSummaries else 0,
'releases': labelSummaries[1] if labelSummaries else 0,
'releaseMedia': labelSummaries[2] if labelSummaries else 0,
'tracks': labelSummaries[3] if labelSummaries else 0,
'length': formatTimeMillisecondsNoDays(labelSummaries[4]) if labelSummaries else "--:--",
'fileSize': sizeof_fmt(labelSummaries[5]) if labelSummaries else "0",
}
labelArtists = conn.execute(text(
"SELECT a.id, a.roadieId, a.name, count(r.id) as releaseCount " +
"FROM `artist` a " +
"join `release` r on r.artistId = a.id " +
"join `releaselabel` rl on rl.releaseId = r.id " +
"join `label` l on l.id = rl.labelId " +
"where l.roadieId = '" + label_id + "' " +
"group by a.id " +
"order by a.name;", autocommit=True)
.columns(artistId=Integer,
artistRoadieId=String,
artistName=String,
releaseCount=Integer
))
return render_template('label.html', label=label, counts=counts, labelArtists=labelArtists)
@app.route('/artist/<artist_id>')
@login_required
def artistDetail(artist_id):
artist = getArtist(artist_id)
if not artist:
return render_template('404.html'), 404
user = getUser()
userArtist = dbSession.query(UserArtist).filter(UserArtist.userId == user.id).filter(
UserArtist.artistId == artist.id).first()
artistSummaries = conn.execute(text(
"SELECT rm.releaseMediaCount, r.releaseCount, ts.trackCount, ts.duration, " +
"ts.size, mts.trackCount AS missingTracks " +
"FROM `artist` a " +
"INNER JOIN " +
"( " +
" select a.id as artistId, count(rm.id) as releaseMediaCount " +
" From `releasemedia` rm " +
" join `release` r on rm.releaseId = r.id " +
" join `artist` a on r.artistId = a.id " +
" group by a.id " +
") as rm ON rm.artistId = a.id " +
"INNER JOIN " +
"( " +
" select a.id as artistId, count(r.id) as releaseCount " +
" from `release` r " +
" join `artist` a on r.artistId = a.id " +
" group by a.id " +
") as r ON r.artistId = a.id " +
"INNER JOIN " +
" ( " +
" SELECT r.artistId AS artistId, COUNT(1) AS trackCount, " +
" SUM(t.duration) AS duration, SUM(t.fileSize) AS size " +
" FROM `track` t " +
" JOIN `releasemedia` rm ON rm.id = t.releaseMediaId " +
" JOIN `release` r ON r.id = rm.releaseId " +
" WHERE t.fileName IS NOT NULL " +
" GROUP BY r.artistId " +
" ) AS ts ON ts.artistId = a.id " +
"LEFT JOIN " +
" ( " +
" SELECT r.artistId AS artistId, COUNT(1) AS trackCount " +
" FROM `track` t " +
" JOIN `releasemedia` rm ON rm.id = t.releaseMediaId " +
" JOIN `release` r ON r.id = rm.releaseId " +
" WHERE t.fileName IS NULL " +
" GROUP BY r.artistId " +
" ) AS mts ON mts.artistId = a.id " +
"WHERE a.roadieId = '" + artist_id + "';", autocommit=True)
.columns(trackCount=Integer, releaseMediaCount=Integer, releaseCount=Integer,
releaseTrackTime=Integer, releaseTrackFileSize=Integer,
missingTrackCount=Integer)) \
.fetchone()
counts = {'tracks': artistSummaries[2] if artistSummaries else 0,
'releaseMedia': artistSummaries[0] if artistSummaries else 0,
'releases': artistSummaries[1] if artistSummaries else 0,
'length': formatTimeMillisecondsNoDays(artistSummaries[3]) if artistSummaries else "--:--",
'fileSize': sizeof_fmt(artistSummaries[4]) if artistSummaries else "0",
'missingTrackCount': artistSummaries[5] if artistSummaries else 0}
artistFolders = conn.execute(text(
"select r.title, t.filePath " +
"from `track` t " +
"join `releasemedia` rm on rm.id = t.releaseMediaId " +
"join `release` r on r.id = rm.releaseId " +
"join `artist` a on a.id = r.artistId " +
"where a.id = " + str(artist.id) + " " +
"group by t.filePath, r.title " +
"order by r.title, t.filePath;"
, autocommit=True).columns(releaseTitle=String, filePath=String))
compilations = dbSession.query(Release) \
.join(ReleaseMedia, ReleaseMedia.releaseId == Release.id) \
.join(Track, Track.releaseMediaId == ReleaseMedia.id) \
.filter(Track.artistId == artist.id).all()
return render_template('artist.html', artist=artist,
releases=sorted(artist.releases, key=lambda rel: str(rel.releaseDate) or ''),
counts=counts, userArtist=userArtist,
artistFolders=artistFolders, compilations=compilations)
def allowed_image_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS
@app.route("/artist/edit/<roadieId>", methods=['GET', 'POST'])
@login_required
def editArtist(roadieId):
try:
isAddingNew = roadieId == NEW_ID
artist = getArtist(roadieId)
if not artist and not isAddingNew:
return render_template('404.html'), 404
if isAddingNew:
artist = Artist()
artist.name = ""
artist.roadieId = NEW_ID
if request.method == 'GET':
return render_template('artistEdit.html', artist=artist)
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
abort(400)
processorBase = ProcessorBase(config, logger)
now = arrow.utcnow().datetime
form = request.form
formFiles = request.files.getlist("fileinput[]")
if formFiles:
for uploadedFile in formFiles:
if uploadedFile.filename:
# Resize to maximum image size and convert to JPEG
img = PILImage.open(io.BytesIO(uploadedFile.read())).convert('RGB')
img.resize(thumbnailSize)
b = io.BytesIO()
img.save(b, "JPEG")
image = Image()
image.status = 2
image.artistId = artist.id
image.roadieId = str(uuid.uuid4())
image.image = b.getvalue()
image.signature = image.averageHash()
dbSession.add(image)
originalArtistFolder = processorBase.artistFolder(artist)
originalName = artist.name
artist.isLocked = False
if 'isLocked' in form and form['isLocked'] == "on":
artist.isLocked = True
artist.name = form['name']
artist.sortName = form['sortName']
artistFolder = processorBase.artistFolder(artist)
if not isAddingNew:
if not isEqual(originalArtistFolder, artistFolder):
for src_dir, dirs, files in os.walk(originalArtistFolder):
dst_dir = src_dir.replace(originalArtistFolder, artistFolder, 1)
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.move(src_file, dst_dir)
if not os.listdir(src_dir):
try:
shutil.rmtree(src_dir)
except:
logger.warn("Unable to Remove Empty Folder [" + src_dir + "]")
pass
try:
if not os.listdir(originalArtistFolder):
shutil.rmtree(originalArtistFolder)
except:
logger.warn("Unable to Remove Empty Folder [" + originalArtistFolder + "]")
pass
dbOriginalArtistFolder = originalArtistFolder.replace(config['ROADIE_LIBRARY_FOLDER'], "", 1)
dbArtistFolder = artistFolder.replace(config['ROADIE_LIBRARY_FOLDER'], "", 1)
if not isEqual(dbOriginalArtistFolder, dbArtistFolder):
for release in artist.releases:
for media in release.media:
for track in media.tracks:
if track.filePath:
track.filePath = track.filePath.replace(dbOriginalArtistFolder, dbArtistFolder, 1)
track.lastUpdated = now
artist.realName = form['realName']
artist.musicBrainzId = form['musicBrainzId']
artist.iTunesId = form['iTunesId']
artist.amgId = form['amgId']
artist.spotifyId = form['spotifyId']
formProfile = form['profile']
if formProfile:
artist.profile = formProfile.strip()
artist.bioContext = form['bioContext']
artist.birthDate = form['birthDate']
artist.endDate = form['endDate']
artist.beginDate = form['beginDate']
artist.artistType = form['artistType']
artist.tags = []
if 'tagsTokenfield' in form:
formtags = form['tagsTokenfield']
if formtags:
for tag in formtags.split('|'):
artist.tags.append(tag)
artist.alternateNames = []
if not isEqual(originalName, artist.name):
artist.alternateNames.append(originalName)
if 'alternateNamesTokenfield' in form:
formAlternateNames = form['alternateNamesTokenfield']
if formAlternateNames:
for alternateName in formAlternateNames.split('|'):
if not isEqual(originalName, alternateName):
artist.alternateNames.append(alternateName)
artist.urls = []
if 'urlsTokenfield' in form:
formUrls = form['urlsTokenfield']
if formUrls:
for url in formUrls.split('|'):
artist.urls.append(url)
artist.isniList = []
if 'isniTokenfield' in form:
formIsniTokenfield = form['isniTokenfield']
if formIsniTokenfield:
for isni in formIsniTokenfield.split('|'):
artist.isniList.append(isni)
artist.associatedArtists = []
if 'associatedArtistsTokenfield' in form:
formAssociatedArtistsTokenfield = form['associatedArtistsTokenfield']
if formAssociatedArtistsTokenfield:
for formAssociatedArtist in formAssociatedArtistsTokenfield.split('|'):
aa = dbSession.query(Artist).filter(Artist.name == formAssociatedArtist).first()
if aa:
artist.associatedArtists.append(aa)
artist.genres = []
if 'genresTokenfield' in form:
formGenresTokenfield = form['genresTokenfield']
if formGenresTokenfield:
for formGenresToken in formGenresTokenfield.split('|'):
genre = dbSession.query(Genre).filter(Genre.name == formGenresToken).first()
if genre:
artist.genres.append(genre)
if not isAddingNew:
artist.lastUpdated = now
else:
artist.roadieId = str(uuid.uuid4())
roadieId = artist.roadieId
dbSession.add(artist)
dbSession.commit()
flash('Artist Edited successfully')
except:
logger.exception("Error Editing Artist")
flash('Error Editing Artist')
dbSession.rollback()
return redirect("/artist/" + roadieId)
@app.route("/user/artist/setrating/<artist_id>/<rating>", methods=['POST'])
@login_required
def setUserArtistRating(artist_id, rating):
try:
artist = getArtist(artist_id)
user = getUser()
if not artist or not user:
return jsonify(message="ERROR")
now = arrow.utcnow().datetime
userArtist = getUserArtistRating(artist.id)
userArtist.rating = rating
userArtist.lastUpdated = now
dbSession.commit()
# Update artist average rating
artistAverage = dbSession.query(func.avg(UserArtist.rating)).filter(UserArtist.artistId == artist.id).scalar()
artist.rating = artistAverage
artist.lastUpdated = now
dbSession.commit()
return jsonify(message="OK", average=artistAverage)
except:
logger.exception("Error Setting Artist Rating")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/user/artist/toggledislike/<artist_id>/<toggle>", methods=['POST'])
@login_required
def toggleUserArtistDislike(artist_id, toggle):
try:
artist = getArtist(artist_id)
user = getUser()
if not artist or not user:
return jsonify(message="ERROR")
now = arrow.utcnow().datetime
userArtist = getUserArtistRating(artist.id)
userArtist.isDisliked = toggle.lower() == "true"
userArtist.lastUpdated = now
if userArtist.isDisliked:
userArtist.rating = 0
dbSession.commit()
# Update artist average rating
artistAverage = dbSession.query(func.avg(UserArtist.rating)).filter(UserArtist.artistId == artist.id).scalar()
artist.rating = artistAverage
artist.lastUpdated = now
dbSession.commit()
return jsonify(message="OK", average=artistAverage)
except:
logger.exception("Error Setting Artist Dislike")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/separatesinglereleases", methods=['POST'])
@login_required
def separateSingleReleases():
try:
for separateSingleRelease in dbSession.query(Release).filter(Release.trackCount == 1):
doDelete = True
for media in separateSingleRelease.media:
if len(media.tracks) == 1:
try:
for track in media.tracks:
try:
fullPath = pathToTrack(track)
newFileName = os.path.join(config['ROADIE_SINGLE_ARTIST_HOLDING_FOLDER'],
str(track.id) + "." +
track.fullPath().replace("\\", "_").replace("/", "_"))
logger.info("= Moving to Single Release Folder [" + newFileName + "]")
shutil.move(fullPath, newFileName)
doDelete = True
except:
pass
except:
pass
if doDelete:
separateSingleRelease.genres = []
logger.info("x Separate Single Release: Deleting Release [" + str(separateSingleRelease.id) + "]")
dbSession.delete(separateSingleRelease)
dbSession.commit()
return jsonify(message="OK")
except:
logger.exception("Error Separate Single Release Favorite")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/user/artist/togglefavorite/<artist_id>/<toggle>", methods=['POST'])
@login_required
def toggleUserArtistFavorite(artist_id, toggle):
try:
artist = getArtist(artist_id)
now = arrow.utcnow().datetime
userArtist = getUserArtistRating(artist.id)
userArtist.isFavorite = toggle.lower() == "true"
userArtist.lastUpdated = now
dbSession.commit()
return jsonify(message="OK")
except:
logger.exception("Error Toggling Favorite")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/release/movetrackstocd/<release_id>/<selected_to_cd>", methods=['POST'])
@login_required
def moveTracksToCd(release_id, selected_to_cd):
try:
moveTracksToCdRelease = getRelease(release_id)
user = getUser()
tracksToMove = request.form['tracksToMove']
if not moveTracksToCdRelease or not user or not tracksToMove:
return jsonify(message="ERROR")
releaseMediaNumber = int(selected_to_cd)
tracksToMove = tracksToMove.split(',')
now = arrow.utcnow().datetime
# Ensure that a release media exists for the release for the given releaseMediaNumber
releaseMedia = dbSession.query(ReleaseMedia) \
.filter(ReleaseMedia.releaseId == moveTracksToCdRelease.id). \
filter(ReleaseMedia.releaseMediaNumber == releaseMediaNumber).first()
if not releaseMedia:
releaseMedia = ReleaseMedia()
releaseMedia.releaseId = moveTracksToCdRelease.id
releaseMedia.roadieId = str(uuid.uuid4())
releaseMedia.releaseMediaNumber = releaseMediaNumber
releaseMedia.trackCount = len(tracksToMove)
dbSession.add(releaseMedia)
releaseMedia.lastUpdated = now
dbSession.commit()
for trackToMove in tracksToMove:
track = getTrack(trackToMove)
if track:
track.releaseMediaId = releaseMedia.id
track.lastUpdated = now
dbSession.commit()
return jsonify(message="OK")
except:
logger.exception("Error In Move Tracks To Cd")
dbSession.rollback()
return jsonify(message="ERROR")
@app.route("/user/release/setrating/<release_id>/<rating>", methods=['POST'])
@login_required
def setUserReleaseRating(release_id, rating):
try:
settUserReleaseRatingRelease = getRelease(release_id)
user = getUser()
if not settUserReleaseRatingRelease or not user:
return jsonify(message="ERROR")
now = arrow.utcnow().datetime
userRelease = getUserReleaseRating(settUserReleaseRatingRelease.id)
userRelease.rating = rating
userRelease.lastUpdated = now