Пример #1
0
def renamePlaylist(request):
    if request.method == 'POST':
        user = request.user
        response = json.loads(request.body)
        if 'PLAYLIST_ID' in response and 'PLAYLIST_NAME' in response:
            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)):
                    deleteView(playlist)
                    playlist.name = strip_tags(response['PLAYLIST_NAME'])
                    playlist.refreshView = True
                    playlist.save()
                    data = {
                        'PLAYLIST_ID': playlist.id,
                        'PLAYLIST_NAME': playlist.name,
                    }
                    data = {**data, **errorCheckMessage(True, None, renamePlaylist)}
                else:
                    data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, renamePlaylist, user)
            else:
                data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, renamePlaylist, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, renamePlaylist, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, renamePlaylist)
    return JsonResponse(data)
Пример #2
0
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)
Пример #3
0
def setPlaylistDescription(request):
    if request.method == "POST":
        response = json.loads(request.body)
        user = request.user
        if 'PLAYLIST_ID' in response and 'PLAYLIST_DESC':
            playlistId = strip_tags(response['PLAYLIST_ID'])
            if Playlist.objects.filter(id=playlistId).count() == 1:
                playlist = Playlist.objects.get(id=playlistId)

                # Checking if it's a library
                if playlist.isLibrary:
                    if not checkPermission(['LIBR'], user):
                        return errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, setPlaylistDescription, user)
                else:
                    # playlist edition
                    if not checkPermission(['PLST'], user):
                        return errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, setPlaylistDescription, user)
                playlist.description = strip_tags(response['PLAYLIST_DESC'])
                playlist.save()

                data = errorCheckMessage(True, None, setPlaylistDescription)
            else:
                data = errorCheckMessage(False, ErrorEnum.DB_ERROR, setPlaylistDescription)
        else:
            data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, setPlaylistDescription, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, setPlaylistDescription)
    return JsonResponse(data)
Пример #4
0
def getWishes(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        user = request.user
        if checkPermission(["WISH"], user):
            if 'ALL' in response:
                allWishes = bool(strip_tags(response['ALL']))

                if checkPermission(["WISR"], user) 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,
                        'USERNAME': wish.user.username,
                        'STATUS': wish.status,
                    })

                data = {**dict({'RESULT': data}), **errorCheckMessage(True, None)}
            else:
                data = errorCheckMessage(False, "badFormat")
        else:
            data = errorCheckMessage(False, "permissionError")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Пример #5
0
def setPlaylistDescription(request):
    if request.method == "POST":
        response = json.loads(request.body)
        user = request.user
        if 'PLAYLIST_ID' in response and 'PLAYLIST_DESC':
            playlistId = strip_tags(response['PLAYLIST_ID'])
            if Playlist.objects.filter(id=playlistId).count() == 1:
                playlist = Playlist.objects.get(id=playlistId)

                # Checking if it's a library
                if playlist.isLibrary:
                    if not checkPermission(['LIBR'], user):
                        return errorCheckMessage(False, "permissionError")
                else:
                    # playlist edition
                    if not checkPermission(['PLST'], user):
                        return errorCheckMessage(False, "permissionError")
                playlist.description = strip_tags(response['PLAYLIST_DESC'])
                playlist.save()

                data = errorCheckMessage(True, None)
            else:
                data = errorCheckMessage(False, "dbError")
        else:
            data = errorCheckMessage(False, "badFormat")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Пример #6
0
def deleteCollection(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        user = request.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)

                # Library deletion
                if playlist.isLibrary:
                    if checkPermission(["LIBR"], user):
                        if Library.objects.filter(
                                playlist=playlist).count() == 1:
                            deleteView(playlist)
                            deleteLibrary(
                                Library.objects.get(playlist=playlist))
                            data = errorCheckMessage(True, None,
                                                     deleteCollection)
                        else:
                            data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                                     deleteCollection)
                    else:
                        data = errorCheckMessage(False,
                                                 ErrorEnum.PERMISSION_ERROR,
                                                 deleteCollection, user)

                # Playlist deletion
                else:
                    if playlist.user == user and checkPermission(["PLST"],
                                                                 user):
                        deleteView(playlist)
                        playlist.delete()
                        data = errorCheckMessage(True, None, deleteCollection)
                    else:
                        data = errorCheckMessage(False,
                                                 ErrorEnum.PERMISSION_ERROR,
                                                 deleteCollection, user)

            else:
                data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                         deleteCollection)
        else:
            data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                     deleteCollection, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST,
                                 deleteCollection)
    return JsonResponse(data)
Пример #7
0
def removeUser(request):
    if request.method == 'POST':
        user = request.user
        if checkPermission(["ADMV"], user):
            response = json.loads(request.body)
            if 'USER_ID' in response:
                try:
                    userId = int(strip_tags(response['USER_ID']))
                    if userId != user.id:
                        if User.objects.filter(id=userId).count() == 1:
                            user = User.objects.get(id=userId)
                            deleteLinkedEntities(user)
                            user.delete()
                            data = errorCheckMessage(True, None)
                        else:
                            data = errorCheckMessage(False, "dbError")
                    else:
                        data = errorCheckMessage(False, "userDeleteError")
                except ValueError:
                    data = errorCheckMessage(False, "valueError")
            else:
                data = errorCheckMessage(False, "badFormat")
        else:
            data = errorCheckMessage(False, "permissionError")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Пример #8
0
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, getLastSongPlayed)
                    }
                else:
                    data = errorCheckMessage(False, ErrorEnum.NO_HISTORY,
                                             getLastSongPlayed, user)
            else:
                data = errorCheckMessage(False, ErrorEnum.NO_HISTORY,
                                         getLastSongPlayed, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     getLastSongPlayed, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST,
                                 getLastSongPlayed)
    return JsonResponse(data)
Пример #9
0
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)
Пример #10
0
def editUserGroup(request):
    if request.method == 'POST':
        user = request.user
        response = json.loads(request.body)
        if checkPermission(["GAPR"], user):
            if 'GROUP_ID' in response and 'USER_ID' in response:
                userId = strip_tags(response['USER_ID'])
                groupId = strip_tags(response['GROUP_ID'])
                if User.objects.filter(id=userId).count() == 1:
                    user = User.objects.get(id=userId)
                    userPref = UserPreferences.objects.get(user=user)
                    if Groups.objects.filter(id=groupId).count() == 1:
                        userPref.group = Groups.objects.get(id=groupId)
                        userPref.save()
                        data = errorCheckMessage(True, None)
                    else:
                        data = errorCheckMessage(False, "dbError")
                else:
                    data = errorCheckMessage(False, "dbError")
            else:
                data = errorCheckMessage(False, "badFormat")
        else:
            data = errorCheckMessage(False, "permissionError")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Пример #11
0
def getMoodbar(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        user = request.user
        if checkPermission(["PLAY"], user):
            if 'TRACK_ID' in response:
                trackID = response['TRACK_ID']
                if Track.objects.filter(id=trackID).count() == 1:
                    track = Track.objects.get(id=trackID)
                    data = {
                        'TRACK_MOOD': track.moodbar,
                    }
                    data = {
                        **data,
                        **errorCheckMessage(True, None, getMoodbar)
                    }
                else:
                    data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                             getMoodbar)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         getMoodbar, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     getMoodbar, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, getMoodbar)
    return JsonResponse(data)
Пример #12
0
def getUserPrefGenres(request):
    if request.method == 'GET':
        user = request.user
        if checkPermission(["STAT"], user):
            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[:100],
                    'LEAST_GENRES': genreTuple[:100],
                }
                data = {**data, **errorCheckMessage(True, None)}
        else:
            data = errorCheckMessage(False, "permissionError")
    else:
        data = errorCheckMessage(False, "")
    return JsonResponse(data)
Пример #13
0
def getUserPrefArtists(request):
    if request.method == 'GET':
        user = request.user
        if checkPermission(["STAT"], user):
            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[:100],
                    'LEAST_ARTISTS': artistCounter[:100],
                }
                data = {**data, **errorCheckMessage(True, None)}
        else:
            data = errorCheckMessage(False, "permissionError")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Пример #14
0
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, randomNextTrack)}
                            return JsonResponse(data)
                        else:
                            count += 1
                data = errorCheckMessage(False, ErrorEnum.DB_ERROR, randomNextTrack)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, randomNextTrack, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, randomNextTrack, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, randomNextTrack)
    return JsonResponse(data)
Пример #15
0
def adminGetUserStats(request):
    if request.method == 'GET':
        user = request.user
        data = []
        if checkPermission(["STAA"], user):
            for user in User.objects.all():
                nbTrackListened = getUserNbTrackListened(user)
                temp = {
                    'USERNAME':
                    user.username,
                    'PREF_ARTIST':
                    getUserPrefArtists(user, True)[:10],
                    'LEAST_ARTISTS':
                    getUserPrefArtists(user, False)[:10],
                    'NB_TRACK_LISTENED':
                    nbTrackListened,
                    'NB_TRACK_PUSHED':
                    getUserNbTrackPushed(user),
                    'PREF_GENRE':
                    getUserPrefGenres(user, nbTrackListened, True)[:10],
                    'LEAST_GENRE':
                    getUserPrefGenres(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)
Пример #16
0
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, ErrorEnum.DB_ERROR,
                                                 getTracksDetailedInfo)
                        return JsonResponse(data)
                data = {
                    **dict({'RESULT': trackInfo}),
                    **errorCheckMessage(True, None, getTracksDetailedInfo)
                }
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         getTracksDetailedInfo, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     getTracksDetailedInfo, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST,
                                 getTracksDetailedInfo)
    return JsonResponse(data)
Пример #17
0
def shuffleNextTrack(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        user = request.user
        if checkPermission(["PLAY"], user):
            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,
                        'IS_LAST': playlistEnd,
                    }
                    data = {**data, **errorCheckMessage(True, None, shuffleNextTrack)}
                else:
                    data = errorCheckMessage(False, ErrorEnum.DB_ERROR, shuffleNextTrack)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, shuffleNextTrack, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, shuffleNextTrack, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, shuffleNextTrack)
    return JsonResponse(data)
Пример #18
0
def getDownloadLocation(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        user = request.user
        if checkPermission(["DOWN"], user):
            if 'TRACK_ID' in response:
                trackId = strip_tags(response['TRACK_ID'])
                if Track.objects.filter(id=trackId).count() == 1:
                    track = Track.objects.get(id=trackId)
                    track.downloadCounter += 1
                    track.save()
                    data = {
                        'DOWNLOAD_PATH': track.location,
                    }
                    data = {
                        **data,
                        **errorCheckMessage(True, None, getDownloadLocation)
                    }
                else:
                    data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                             getDownloadLocation)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         getDownloadLocation, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     getDownloadLocation, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST,
                                 getDownloadLocation)
    return JsonResponse(data)
Пример #19
0
def editUserGroup(request):
    if request.method == 'POST':
        user = request.user
        response = json.loads(request.body)
        if checkPermission(["GAPR"], user):
            if 'GROUP_ID' in response and 'USER_ID' in response:
                userId = strip_tags(response['USER_ID'])
                groupId = strip_tags(response['GROUP_ID'])
                if User.objects.filter(id=userId).count() == 1:
                    user = User.objects.get(id=userId)
                    userPref = UserPreferences.objects.get(user=user)
                    if Groups.objects.filter(id=groupId).count() == 1:
                        userPref.group = Groups.objects.get(id=groupId)
                        userPref.save()
                        data = errorCheckMessage(True, None, editUserGroup)
                    else:
                        data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                                 editUserGroup)
                else:
                    data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                             editUserGroup)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         editUserGroup, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     editUserGroup, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, editUserGroup)
    return JsonResponse(data)
Пример #20
0
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)
Пример #21
0
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)
Пример #22
0
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)
Пример #23
0
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)
Пример #24
0
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)
Пример #25
0
def removeUser(request):
    if request.method == 'POST':
        user = request.user
        if checkPermission(["ADMV"], user):
            response = json.loads(request.body)
            if 'USER_ID' in response:
                try:
                    userId = int(strip_tags(response['USER_ID']))
                    if userId != user.id:
                        if User.objects.filter(id=userId).count() == 1:
                            user = User.objects.get(id=userId)
                            deleteLinkedEntities(user)
                            user.delete()
                            data = errorCheckMessage(True, None, removeUser)
                        else:
                            data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                                     removeUser)
                    else:
                        data = errorCheckMessage(False,
                                                 ErrorEnum.USER_DELETE_ERROR,
                                                 removeUser, user)
                except ValueError:
                    data = errorCheckMessage(False, ErrorEnum.VALUE_ERROR,
                                             removeUser, user)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         removeUser, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     removeUser, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, removeUser)
    return JsonResponse(data)
Пример #26
0
def handleUploadedFile(request):
    if request.method == 'POST':
        user = request.user
        response = json.loads(request.body)
        if checkPermission(["UPLD"], user):
            if 'CONTENT' in response and 'FILENAME' in response:
                name = strip_tags(response['FILENAME'])
                if '/' not in name and '\\' not in name:
                    adminOptions = getAdminOptions()
                    if not os.path.exists(adminOptions.bufferPath):
                        try:
                            os.makedirs(adminOptions.bufferPath)
                        except os.error:
                            return JsonResponse(errorCheckMessage(False, "dNdError"))
                    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, "permissionError")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Пример #27
0
def changeBufferPath(request):
    if request.method == 'POST':
        user = request.user
        if checkPermission(["ADMV"], user):
            response = json.loads(request.body)
            if 'BUFFER_PATH' in response:
                adminOptions = getAdminOptions()
                bufferPath = strip_tags(response['BUFFER_PATH'])
                if os.path.isdir(bufferPath):
                    adminOptions.bufferPath = bufferPath
                    adminOptions.save()
                    data = errorCheckMessage(True, None, changeBufferPath)
                else:
                    data = errorCheckMessage(False, ErrorEnum.DIR_NOT_FOUND,
                                             changeBufferPath)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         changeBufferPath, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     changeBufferPath, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST,
                                 changeBufferPath)
    return JsonResponse(data)
Пример #28
0
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)
Пример #29
0
def multiTrackDownload(request):
    if request.method == "POST":
        response = json.loads(request.body)
        user = request.user
        if checkPermission(["DOWN"], user):
            if 'TRACKS_ID' in response:
                trackIds = response['TRACKS_ID']
                # TODO : create admin option max number of sound to download
                if len(trackIds) > 50:
                    return JsonResponse(
                        errorCheckMessage(False, None, multiTrackDownload))
                locations = []

                # Getting tracks requested by the user
                for trackId in trackIds:
                    if Track.objects.filter(id=trackId).count() == 1:
                        track = Track.objects.get(id=trackId)
                        locations.append(track.location)
                tmp = ""
                for loc in locations:
                    tmp += loc
                archiveName = "ManaZeak-" + str(
                    zlib.crc32(tmp.encode("ascii", "ignore"))) + ".zip"

                # Checking if the output folder for the zip exists
                if not os.path.isdir("/static/zip"):
                    try:
                        os.makedirs("/static/zip")
                    except OSError:
                        return JsonResponse(
                            errorCheckMessage(False,
                                              ErrorEnum.DIR_CREATION_ERROR,
                                              multiTrackDownload))

                # Creating archive
                archiveName = os.path.join("/static/zip", archiveName)
                archive = zipfile.ZipFile(archiveName, 'w',
                                          zipfile.ZIP_DEFLATED)
                for location in locations:
                    archive.write(location,
                                  os.path.basename(location),
                                  compress_type=zipfile.ZIP_DEFLATED)

                data = {
                    **{
                        'DOWNLOAD_PATH': archiveName,
                    },
                    **errorCheckMessage(True, None)
                }
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         multiTrackDownload)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     multiTrackDownload, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST,
                                 multiTrackDownload)
    return JsonResponse(data)
Пример #30
0
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, getTrackPath)
                    }
                else:
                    data = errorCheckMessage(False, ErrorEnum.DB_ERROR,
                                             getTrackPath)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         getTrackPath, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     getTrackPath, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, getTrackPath)
    return JsonResponse(data)