def shuffleNextTrack(request): if request.method == 'POST': response = json.loads(request.body) if 'PLAYLIST_ID' in response: if Shuffle.objects.filter( playlist=Playlist.objects.get(id=response['PLAYLIST_ID']), user=request.user).count() == 1: shuffle = Shuffle.objects.get( playlist=Playlist.objects.get(id=response['PLAYLIST_ID']), user=request.user) else: shuffle = Shuffle( playlist=Playlist.objects.get(id=response['PLAYLIST_ID']), user=request.user) shuffle.save() track, playlistEnd = shuffleSoundSelector(shuffle) shuffle.tracksPlayed.add(track) shuffle.save() if Track.objects.filter(id=track.id).count() == 1: data = { 'TRACK_ID': track.id, 'PATH': track.location, 'COVER': track.coverLocation, 'LAST': playlistEnd, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def handleUploadedFile(request): if request.method == 'POST': user = request.user response = json.loads(request.body) if 'CONTENT' in response and 'NAME' in response: name = strip_tags(response['NAME']) if '/' not in name and '\\' not in name: adminOptions = getAdminOptions() if not os.path.exists(adminOptions.bufferPath): os.makedirs(adminOptions.bufferPath) filePath = os.path.join(adminOptions.bufferPath, name) if not os.path.isfile(filePath): with open(filePath, 'wb+') as destination: # Split the header with MIME type destination.write(base64.b64decode(str(response['CONTENT'].split(",")[1]))) setUploader(filePath, user.username) data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "fileExists") else: data = errorCheckMessage(False, "badFileName") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getUserPrefArtists(request): if request.method == 'GET': user = request.user artists = Artist.objects.all() artistCounter = [] for artist in artists: counter = 0 stats = Stats.objects.filter(track__artist=artist, user=user) for track in stats: counter += track.playCounter artistCounter.append((artist.name, counter)) artistCounter.sort(key=itemgetter(1), reverse=True) prefArtists = copy.deepcopy(artistCounter) artistCounter.sort(key=itemgetter(1), reverse=False) if len(prefArtists) == 0: data = errorCheckMessage(True, "noStats") else: data = { 'PREF_ARTISTS': prefArtists[:25], 'LEAST_ARTISTS': artistCounter[:25], } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getUserPrefGenres(request): if request.method == 'GET': genres = Genre.objects.all() genreTuple = [] user = request.user numberPlayedTrack = getUserNbTrackListened(user) for genre in genres: counter = 0 tracks = Stats.objects.filter(track__genre=genre, user=user) for track in tracks: counter += track.playCounter if numberPlayedTrack != 0: genreTuple.append( (genre.name, counter, (counter / numberPlayedTrack) * 100)) else: genreTuple.append((genre.name, counter, 0)) genreTuple.sort(key=itemgetter(1), reverse=True) prefGenres = copy.deepcopy(genreTuple) genreTuple.sort(key=itemgetter(1), reverse=False) if len(prefGenres) == 0: data = errorCheckMessage(True, "noStats") else: data = { 'PREF_GENRES': prefGenres[:25], 'LEAST_GENRES': genreTuple[:25], } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "") return JsonResponse(data)
def getWishes(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if 'ALL' in response: allWishes = bool(strip_tags(response['ALL'])) if user.is_superuser and allWishes: wishes = Wish.objects.all().order_by('-id') else: wishes = Wish.objects.filter(user=user).order_by('-id') data = [] for wish in wishes: data.append({ 'WISH_ID': wish.id, 'DATE': wish.date, 'TEXT': wish.text, 'USER': wish.user.username, 'STATUS': wish.status, }) data = {**dict({'RESULT': data}), **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def newLibrary(request): if request.method == 'POST': if request.user.is_superuser: response = json.loads(request.body) if 'URL' in response and 'NAME' in response and 'CONVERT' in response: dirPath = response['URL'] if os.path.isdir(dirPath): # Removing / at the end of the dir path if present if dirPath.endswith("/"): dirPath = dirPath[:-1] library = Library() library.path = dirPath library.name = strip_tags(response['NAME']) library.convertID3 = response['CONVERT'] library.user = request.user library.save() data = { 'LIBRARY_ID': library.id, 'NAME': library.name, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dirNotFound") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getUserPrefTracks(request): if request.method == 'GET': user = request.user statsPref = Stats.objects.filter(user=user).order_by( '-playCounter', '-listeningPercentage') statsLeast = Stats.objects.filter(user=user).order_by( 'playCounter', 'listeningPercentage') trackTuplePref = [] trackTupleLeast = [] for stat in statsPref: if stat.listeningPercentage is not None: trackTuplePref.append( (stat.track.title, stat.playCounter, stat.listeningPercentage / stat.playCounter)) else: trackTuplePref.append((stat.track.title, stat.playCounter, 0)) for stat in statsLeast: if stat.listeningPercentage is not None: trackTupleLeast.append( (stat.track.title, stat.playCounter, stat.listeningPercentage / stat.playCounter)) else: trackTupleLeast.append((stat.track.title, stat.playCounter, 0)) if len(trackTuplePref) == 0: data = errorCheckMessage(True, "noStats") else: data = { 'PREF_TRACKS': trackTuplePref[:25], 'LEAST_TRACKS': trackTupleLeast[:25], } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getTracksDetailedInfo(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if checkPermission(["PLAY"], user): if 'TRACK_ID' in response: trackIds = response['TRACK_ID'] trackInfo = [] for trackId in trackIds: if Track.objects.filter(id=trackId).count() == 1: trackInfo.append( exportTrackInfo(Track.objects.get(id=trackId))) else: data = errorCheckMessage(False, "dbError") return JsonResponse(data) data = { **dict({'RESULT': trackInfo}), **errorCheckMessage(True, None) } else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def renamePlaylist(request): if request.method == 'POST': response = json.loads(request.body) if 'PLAYLIST_ID' in response and 'PLAYLIST_NAME' in response: user = request.user playlistId = strip_tags(response['PLAYLIST_ID']) if Playlist.objects.filter(id=playlistId, user=user).count() == 1: playlist = Playlist.objects.get(id=playlistId, user=user) if (checkPermission(["PLST"], user) and not playlist.isLibrary) \ or (playlist.isLibrary and checkPermission(["LIBR"], user)): playlist.name = strip_tags(response['PLAYLIST_NAME']) playlist.save() data = { 'PLAYLIST_ID': playlist.id, 'PLAYLIST_NAME': playlist.name, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getPlaylistInfo(request): if request.method == 'POST': response = json.loads(request.body) if 'PLAYLIST_ID' in response: playlistId = strip_tags(response['PLAYLIST_ID']) if Playlist.objects.filter(id=playlistId).count() == 1: playlist = Playlist.objects.get(id=playlistId) artists = set() genres = set() bitRate = 0 for track in playlist.track: artists.add(track.artist) genres.add(track.genre) bitRate += track.bitRate bitRate = bitRate / len(playlist.track) data = { 'TRACK_TOTAL': playlist.track.count(), 'ARTIST_TOTAL': len(artists), 'GENRE_TOTAL': len(genres), 'AVERAGE_BIT_RATE': bitRate, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def addTracksToPlaylist(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if 'PLAYLIST_ID' in response and 'TRACKS_ID' in response: tracksId = response['TRACKS_ID'] playlistId = strip_tags(response['PLAYLIST_ID']) if Playlist.objects.filter(id=playlistId).count() == 1: playlist = Playlist.objects.get(id=playlistId) # Checking permissions if not playlist.isLibrary and checkPermission( ["PLST"], user) and playlist.user == user: tracks = Track.objects.filter(id__in=tracksId) for track in tracks: playlist.track.add(track) # Set rescan flag for view generation playlist.refreshView = True playlist.save() data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def rescanLibrary(request): if request.method == 'POST': response = json.loads(request.body) if 'LIBRARY_ID' in response: library = strip_tags(response['LIBRARY_ID']) if Library.objects.filter(id=library).count() == 1: library = Library.objects.get(id=library) # Check if the library is not used somewhere else if library.playlist.isScanned: # Delete all the old tracks library.playlist.delete() # Recreating playlist playlist = Playlist() playlist.name = library.name playlist.user = request.user playlist.isLibrary = True playlist.save() library.playlist = playlist library.save() # Scan library data = scanLibrary(library, playlist, library.convertID3) else: data = errorCheckMessage(False, "rescanError") else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def isAdmin(request): if request.method == 'GET': data = {'IS_ADMIN': request.user.is_superuser} data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def adminGetUserStats(request): if request.method == 'GET': admin = request.user data = [] if admin.is_superuser: for user in User.objects.all(): nbTrackListened = getUserNbTrackListened(user) temp = { 'USERNAME': user.username, 'PREF_ARTIST': getUserPrefArtist(user, True)[:10], 'LEAST_ARTISTS': getUserPrefArtist(user, False)[:10], 'NB_TRACK_LISTENED': nbTrackListened, 'NB_TRACK_PUSHED': getUserNbTrackPushed(user), 'PREF_GENRE': getUserPrefGenre(user, nbTrackListened, True)[:10], 'LEAST_GENRE': getUserPrefGenre(user, nbTrackListened, False)[:10], 'NEVER_PLAYED': userNeverPlayed(user), } data.append(temp) data = {**dict({'RESULT': data}), **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def isInviteEnabled(request): if request.method == 'GET': data = {'INVITE': getAdminOptions().inviteCodeEnabled} data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def newLibrary(request): if request.method == 'POST': user = request.user if checkPermission(["LIBR"], user): response = json.loads(request.body) if 'URL' in response and 'NAME' in response: dirPath = response['URL'] if os.path.isdir(dirPath): # Removing / at the end of the dir path if present if dirPath.endswith("/"): dirPath = dirPath[:-1] library = Library() library.path = dirPath playlist = Playlist() playlist.user = user playlist.isLibrary = True playlist.name = strip_tags(response['NAME']) playlist.save() library.playlist = playlist library.save() data = { 'LIBRARY_ID': library.id, 'LIBRARY_NAME': library.playlist.name, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dirNotFound") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def randomNextTrack(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if checkPermission(["PLAY"], user): if 'PLAYLIST_ID' in response: playlistID = strip_tags(response['PLAYLIST_ID']) if Playlist.objects.filter(id=playlistID).count() == 1: playlist = Playlist.objects.get(id=playlistID) rangeRand = playlist.track.count() selectedTrack = randint(0, rangeRand) count = 0 for track in playlist.track.all(): if count == selectedTrack: data = { 'TRACK_ID': track.id, } data = {**data, **errorCheckMessage(True, None)} return JsonResponse(data) else: count += 1 data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def toggleRandom(request): if request.method == 'POST': response = json.loads(request.body) if 'RANDOM_MODE' in response and 'PLAYLIST_ID' in response: randomMode = strip_tags(response['RANDOM_MODE']) randomMode = int(randomMode) if randomMode in range(0, 3): user = request.user playlistId = strip_tags(response['PLAYLIST_ID']) if Playlist.objects.filter(id=playlistId).count() == 1: playlist = Playlist.objects.get(id=playlistId) if PlaylistSettings.objects.filter(playlist=playlist, user=user).count() == 1: settings = PlaylistSettings.objects.get( playlist=playlist, user=user) else: settings = PlaylistSettings() settings.user = user # TODO : change to right view mode settings.viewMode = 0 settings.playlist = playlist settings.randomMode = randomMode settings.save() data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getLastSongPlayed(request): if request.method == 'GET': user = request.user if checkPermission(["PLAY"], user): if UserHistory.objects.filter(user=user).count() != 0: userHistory = UserHistory.objects.get(user=user) if userHistory.histories.count() != 0: trackId = 0 for history in userHistory.histories.order_by('-date'): trackId = history.track.id history.delete() break data = { 'TRACK_ID': trackId, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "noHistory") else: data = errorCheckMessage(False, "noHistory") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def removeTracksFromPlaylist(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if 'PLAYLIST_ID' in response and 'TRACKS_ID' in response: tracksId = response['TRACKS_ID'] playlistId = strip_tags(response['PLAYLIST_ID']) if Playlist.objects.filter(id=playlistId).count() == 1: playlist = Playlist.objects.get(id=playlistId) if checkPermission([ "PLST" ], user) and user == playlist.user and not playlist.isLibrary: tracks = Track.objects.filter(id__in=tracksId) for track in tracks: playlist.track.remove(track) data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def changeTracksMetadata(request): if request.method == 'POST': user = request.user response = json.loads(request.body) if checkPermission(["TAGE"], user): if 'TRACKS_ID' in response: trackIds = response['TRACKS_ID'] data = {} for trackId in trackIds: trackId = checkIntValueError(trackId) if trackId is not None: if Track.objects.filter(id=trackId).count() == 1: track = Track.objects.get(id=trackId) # Updating database information tags = updateDBInfo(response, track) # Changing tags in the file data = updateFileMetadata(track, tags) for playlist in Playlist.objects.filter(track__id=track.id): if not playlist.refreshView: playlist.refreshView = True playlist.save() else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "valueError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def deleteUser(request): if request.method == 'GET': user = request.user deleteLinkedEntities(user) user.delete() data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def toggleInvite(request): if request.method == 'GET': adminOptions = getAdminOptions() adminOptions.inviteCodeEnabled = not adminOptions.inviteCodeEnabled adminOptions.save() data = {'INVITE': adminOptions.inviteCodeEnabled} data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def rescanAllLibraries(request): if request.method == 'GET': user = request.user if checkPermission(["LIBR"], user): scanThread = Process(target=rescanLibraryProcess, args=None) db.connections.close_all() scanThread.start() data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def removeAllMoods(request): if request.method == 'GET': user = request.user if checkPermission(["ADMV"], user): moodbars = "/ManaZeak/static/mood/" for mood in os.listdir(moodbars): os.remove(os.path.join(moodbars, mood)) data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def checkNamingConventionArtistsOnPlaylist(request): data = {} if request.method == 'POST': user = request.user if user.is_superuser: response = json.loads(request.body) if 'PLAYLIST_ID' in response: playlistId = response['PLAYLIST_ID'] data = set() if Playlist.objects.filter(id=playlistId).count() == 1: tracks = Playlist.objects.get(id=playlistId).track.all() for track in tracks: path, fileName = os.path.split(track.location) splicedName = fileName.split(" - ") # Extracting artists artists = splicedName[0] splicedArtists = artists.split(",") # Checking if the artists are in a good order for i in range(len(splicedArtists) - 1): artist1 = splicedArtists[i].rstrip().lstrip() artist2 = splicedArtists[i + 1].rstrip().lstrip() if artist1[0] > artist2[0]: data.add(track) break # Checking if the title contains caps at the beginning of each word fileName = splicedName[1] words = fileName.split(" ") for word in words: if not word[0].isupper(): data.add(track) break # The tracks contains a featuring if "(feat." in fileName: feats = fileName.split("feat.") for i in range(len(feats) - 1): artist1 = feats[i].rstrip().lstrip() artist2 = feats[i + 1].rstrip().lstrip() if artist1[0] > artist2[0]: data.add(track) break data = dict({'RESULT': data}) data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getAdminView(request): if request.method == 'GET': admin = request.user if admin.is_superuser: adminOptions = getAdminOptions() users = User.objects.all().order_by('date_joined') userInfo = [] for user in users: dateJoined = str(user.date_joined.day).zfill(2) + "/" + str(user.date_joined.month).zfill(2) + \ "/" + str(user.date_joined.year) + " - " + str(user.date_joined.hour) + ":" + \ str(user.date_joined.minute) lastLogin = str(user.last_login.day).zfill(2) + "/" + str(user.last_login.month).zfill(2) + \ "/" + str(user.last_login.year) + " - " + str(user.last_login.hour) + ":" + \ str(user.last_login.minute) userInfo.append({ 'NAME': user.username, 'ADMIN': user.is_superuser, 'JOINED': dateJoined, 'LAST_LOGIN': lastLogin, 'ID': user.id, }) data = dict({'USER': userInfo}) libraryInfo = [] for library in Library.objects.all(): libraryInfo.append({ 'NAME': library.name, 'PATH': library.path, 'NUMBER_TRACK': library.playlist.track.all().count(), 'ID': library.id, }) data = {**data, **dict({'LIBRARIES': libraryInfo})} data = { **data, **{ 'SYNC_KEY': adminOptions.syncthingKey, 'BUFFER_PATH': adminOptions.bufferPath, 'INVITE_ENABLED': adminOptions.inviteCodeEnabled, } } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def deleteAllLibrary(request): if request.method == 'GET': admin = request.user if admin.is_superuser: libraries = Library.objects.all() for library in libraries: library.playlist.track.all().delete() library.playlist.delete() library.delete() data = errorCheckMessage(True, None) else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def checkLibraryScanStatus(request): if request.method == 'POST': response = json.loads(request.body) if 'PLAYLIST_ID' in response: if Playlist.objects.filter( id=response['PLAYLIST_ID']).count() == 1: playlist = Playlist.objects.get(id=response['PLAYLIST_ID']) data = errorCheckMessage(playlist.isScanned, None) else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def getTrackPath(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if checkPermission(["PLAY"], user): # Checking JSON keys if 'TRACK_ID' in response and 'PREVIOUS' in response and 'LAST_TRACK_PATH' in response \ and 'TRACK_PERCENTAGE' in response: trackId = strip_tags(response['TRACK_ID']) # Getting the track asked if Track.objects.filter(id=trackId).count() == 1: track = Track.objects.get(id=trackId) # If we don't ask a previous track if not bool(response['PREVIOUS']): # Adding the current track to the history # Removing the first 2 chars previousTrackPath = strip_tags( response['LAST_TRACK_PATH'])[2:] # If the previous track exists if Track.objects.filter( location=previousTrackPath).count() == 1: listeningPercentage = float( strip_tags(response['TRACK_PERCENTAGE'])) previousTrack = Track.objects.get( location=previousTrackPath) checkListeningGain(previousTrack, user) # Adding to stats if the user has listened more than 15% of the song if listeningPercentage > 5: previousTrack.playCounter += 1 previousTrack.save() addToStats(previousTrack, listeningPercentage, user) addToHistory(track, user) # Returning the asked song data = { 'TRACK_PATH': track.location, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)