Exemplo n.º 1
0
def modLibrary(request, player_id, player):
    try:
        toAdd = json.loads(request.POST['to_add'])
        toDelete = json.loads(request.POST['to_delete'])
    except ValueError as f:
        return HttpResponseBadRequest("Bad JSON. Couldn't even parse. \n" +
                                      "to add data: " +
                                      request.POST['to_add'] + "\n" +
                                      "to delete data: " +
                                      request.POST['to_delete'])

    try:
        duplicates, badIds = getDuplicateDifferentIds(toAdd, player)
        if len(badIds) > 0:
            return HttpJSONResponse(json.dumps(badIds), status=409)

        nonExistentIds = getNonExistantLibIds(toDelete, player)
        if len(nonExistentIds) > 0:
            return HttpJSONResponse(json.dumps(nonExistentIds), status=404)

        addSongs(filter(lambda song: song['id'] not in duplicates, toAdd),
                 player)
        deleteSongs(toDelete, player)
    except KeyError as e:
        return HttpResponseBadRequest('Bad JSON.\n Bad key: ' + str(e))
    except ValueError as f:
        return HttpResponseBadRequest('Bad JSON.\n Bad value: ' + str(f))

    return HttpResponse()
Exemplo n.º 2
0
def multiBan(request, player_id, player):
    try:
        toBan = json.loads(request.POST['to_ban'])
        toUnban = json.loads(request.POST['to_unban'])
    except ValueError:
        return HttpResponseBadRequest("Bad JSON. Couldn't even parse. \n" +
                                      "to add data: " +
                                      request.POST['to_add'] + "\n" +
                                      "to delete data: " +
                                      request.POST['to_delete'])

    nonExistentIds = getNonExistantLibIds(toBan, player)
    nonExistentIds += getNonExistantLibIds(toUnban, player)
    if len(nonExistentIds) > 0:
        toReturn = HttpJSONResponse(json.dumps(nonExistentIds), status=404)
        toReturn[MISSING_RESOURCE_HEADER] = 'song'
        return toReturn

    def setSongBanStatus(songid, banStatus):
        songToBan = LibraryEntry.objects.get(player=player,
                                             player_lib_song_id=songid)
        songToBan.is_banned = banStatus
        songToBan.save()

    map(lambda songid: setSongBanStatus(songid, True), toBan)
    map(lambda songid: setSongBanStatus(songid, False), toUnban)

    return HttpResponse()
Exemplo n.º 3
0
def getNearbyPlayers(request, latitude, longitude):

  search_limit = int(request.GET.get('max_results', 20))
  search_limit = min(search_limit, 100)

  search_radius = int(request.GET.get('radius', default_search_radius))
  if search_radius >= max_search_radius or search_radius < min_search_radius:
    radii_info = { 'min_radius' : min_search_radius, 'max_radius' : max_search_radius}
    return HttpJSONResponse(json.dumps(radii_info), status=406)

  givenLat = float(latitude)
  givenLon = float(longitude)
  point = Point(givenLon, givenLat)

  nearbyLocations = PlayerLocation.objects.exclude(player__state='IN').filter(
    point__distance_lte=(point, D(km=search_radius))).distance(point).order_by('distance')[:search_limit]

  nearbyPlayers = [location.player for location in nearbyLocations]

  return HttpJSONResponse(json.dumps(nearbyPlayers, cls=UDJEncoder))
Exemplo n.º 4
0
def authenticate(request):

  try:
    userToAuth = User.objects.get(username=request.POST['username'])
    if userToAuth.check_password(request.POST['password']):
      ticket = obtainTicketForUser(userToAuth)
      ticket_and_id = {"ticket_hash" : ticket.ticket_hash, "user_id" : userToAuth.id}
      response = HttpJSONResponse(json.dumps(ticket_and_id))
      return response
    else:
      response = HttpResponse(status=401)
      response['WWW-Authenticate'] = 'password'
      return response
  except ObjectDoesNotExist:
    response = HttpResponse(status=401)
    response['WWW-Authenticate'] = 'password'
    return response
Exemplo n.º 5
0
def addSongs2Library(request, player_id, player):

    try:
        libJSON = json.loads(request.raw_post_data)
    except ValueError:
        return HttpResponseBadRequest('Bad JSON')

    try:
        duplicates, badIds = getDuplicateDifferentIds(libJSON, player)
        if len(badIds) > 0:
            return HttpJSONResponse(json.dumps(badIds), status=409)
        else:
            addSongs(
                filter(lambda song: song['id'] not in duplicates, libJSON),
                player)
    except KeyError as e:
        return HttpResponseBadRequest("Bad JSON. Missing key: " + str(e))
    except ValueError as f:
        return HttpResponseBadRequest("Bad JSON. Bad value: " + str(f))

    return HttpResponse(status=201)
Exemplo n.º 6
0
def getBannedUsers(request, player_id, player):
    return HttpJSONResponse(json.dumps(player.BannedUsers(), cls=UDJEncoder))
Exemplo n.º 7
0
def getUsersForPlayer(request, player_id, player):
    return HttpJSONResponse(
        json.dumps(player.ActiveParticipants(), cls=UDJEncoder))
Exemplo n.º 8
0
def getRandomSongsForPlayer(request, player_id, player):
    rand_limit = int(request.GET.get('max_randoms', 40))
    rand_limit = min(rand_limit, 100)
    randomSongs = player.Randoms()[:rand_limit]
    return HttpJSONResponse(json.dumps(randomSongs, cls=UDJEncoder))
Exemplo n.º 9
0
def getRecentlyPlayed(request, player_id, player):
    songs_limit = int(request.GET.get('max_songs', 40))
    songs_limit = min(songs_limit, 100)
    recentlyPlayed = player.RecentlyPlayed()[:songs_limit]
    return HttpJSONResponse(json.dumps(recentlyPlayed, cls=UDJEncoder))
Exemplo n.º 10
0
def getArtistSongs(request, player_id, player, givenArtist):
    return HttpJSONResponse(
        json.dumps(player.ArtistSongs(givenArtist), cls=UDJEncoder))
Exemplo n.º 11
0
def getArtists(request, player_id, player):
    return HttpJSONResponse(json.dumps(player.Artists(), cls=UDJEncoder))
Exemplo n.º 12
0
def getAvailableMusic(request, player_id, player):
    availableMusic = player.AvailableMusic(request.GET['query'])
    if 'max_results' in request.GET:
        availableMusic = availableMusic[:request.GET['max_results']]
    return HttpJSONResponse(json.dumps(availableMusic, cls=UDJEncoder))
Exemplo n.º 13
0
def getSongSetsForPlayer(request, player_id, player):
    return HttpJSONResponse(json.dumps(player.SongSets(), cls=UDJEncoder))
Exemplo n.º 14
0
def getAdminsForPlayer(request, player_id, player):
    return HttpJSONResponse(json.dumps(player.Admins(), cls=UDJEncoder))
Exemplo n.º 15
0
def getPlayers(request):
  search_limit = int(request.GET.get('max_results', 20))
  search_limit = min(search_limit, 100)

  players = Player.objects.filter(name__icontains=request.GET['name']).exclude(state='IN')[:search_limit]
  return HttpJSONResponse(json.dumps(players, cls=UDJEncoder))
Exemplo n.º 16
0
def createPlayer(request):
    user = getUserForTicket(request)
    try:
        newPlayerJSON = json.loads(request.raw_post_data)
    except ValueError:
        return HttpResponseBadRequest('Bad JSON')

    #Ensure the name attribute was provided with the JSON
    try:
        newPlayerName = newPlayerJSON['name']
    except KeyError:
        return HttpResponseBadRequest('No name given')

    #Determine which sorting algorithm to use
    if 'sorting_algorithm_id' in newPlayerJSON:
        try:
            sortingAlgo = SortingAlgorithm.objects.get(
                pk=newPlayerJSON['sorting_algorithm_id'])
        except ObjectDoesNotExist:
            toReturn = HttpResponseNotFound()
            toReturn[MISSING_RESOURCE_HEADER] = 'sorting_algorithm'
            return toReturn
    else:
        try:
            sortingAlgo = SortingAlgorithm.objects.get(
                function_name=default_sorting_algo)
        except ObjectDoesNotExist:
            raise ImproperlyConfigured(
                'Default sorting algorithm is not in database')

    #Determine external library
    externalLib = None
    if 'external_library_id' in newPlayerJSON:
        try:
            externalLib = ExternalLibrary.objects.get(
                pk=newPlayerJSON['external_library_id'])
        except ObjectDoesNotExist:
            toReturn = HttpResponseNotFound()
            toReturn[MISSING_RESOURCE_HEADER] = 'external_library'
            return toReturn

    #Ensure that the suers doesn't already have a player with the given name
    conflictingPlayer = Player.objects.filter(owning_user=user,
                                              name=newPlayerName)
    if conflictingPlayer.exists():
        return HttpResponse('A player with that name already exists',
                            status=409)

    #Create and save new player
    newPlayer = Player(owning_user=user,
                       name=newPlayerName,
                       sorting_algo=sortingAlgo,
                       external_library=externalLib)
    newPlayer.save()

    #If password provided, create and save password
    if 'password' in newPlayerJSON:
        PlayerPassword(player=newPlayer,
                       password_hash=hashPlayerPassword(
                           newPlayerJSON['password'])).save()

    #If locaiton provided, geocode it and save it
    if 'location' in newPlayerJSON:
        location = newPlayerJSON['location']
        if isValidLocation(location):
            try:
                setPlayerLocation(location, newPlayer)
            except LocationNotFoundError:
                return HttpResponseBadRequest('Location not found')
        else:
            return HttpResponseBadRequest('Bad location')

    return HttpJSONResponse(json.dumps({'player_id': newPlayer.id}),
                            status=201)
Exemplo n.º 17
0
def getFavorites(request, player_id):
  user = getUserForTicket(request)
  favorites = Favorite.objects.filter(user=user, favorite_song__player__id=player_id)
  return HttpJSONResponse(json.dumps(favorites, cls=UDJEncoder))
Exemplo n.º 18
0
def getExternalLibraries(request):
    allExternalLibs = ExternalLibrary.objects.all()
    return HttpJSONResponse(json.dumps(allExternalLibs, cls=UDJEncoder))
Exemplo n.º 19
0
def getSortingAlgorithms(request):
    allAlgos = SortingAlgorithm.objects.all()
    return HttpJSONResponse(json.dumps(allAlgos, cls=UDJEncoder))