Ejemplo n.º 1
0
 def wrapper(*args, **kwargs):
   request = args[0]
   user = getUserForTicket(request)
   player = kwargs['player']
   if player.owning_user==user:
     return HttpResponseBadRequest()
   else:
     return function(*args, **kwargs)
Ejemplo n.º 2
0
 def wrapper(*args, **kwargs):
   request = args[0]
   user = getUserForTicket(request)
   player = kwargs['player']
   if player.canCreateSongSets(user):
     return function(*args, **kwargs)
   else:
     return HttpResponseForbidden()
Ejemplo n.º 3
0
 def wrapper(*args, **kwargs):
   request = args[0]
   user = getUserForTicket(request)
   activePlayer = kwargs['activePlayer']
   if activePlayer.owning_user==user:
     return function(*args, **kwargs)
   else:
     return HttpResponseForbidden()
Ejemplo n.º 4
0
def modActivePlaylist(request, player_id, player, lib_id):
  user = getUserForTicket(request)
  if request.method == 'PUT':
    return add2ActivePlaylist(user, lib_id, player)
  elif request.method == 'DELETE':
    if not (user == player.owning_user or player.isAdmin(user)):
      return HttpResponseForbidden()
    return removeFromActivePlaylist(request, user, lib_id, player)
Ejemplo n.º 5
0
 def wrapper(*args, **kwargs):
   request = args[0]
   user = getUserForTicket(request)
   player = kwargs['player']
   if player.owning_user==user or player.isAdmin(user):
     return function(*args, **kwargs)
   else:
     return HttpResponseForbidden()
Ejemplo n.º 6
0
def favorite(request, player_id, lib_id):
  user = getUserForTicket(request)
  if request.method == 'PUT':
    return addSongToFavorite(user, player_id, lib_id)
  elif request.method == 'DELETE':
    return removeSongFromFavorite(user, player_id, lib_id)
  else:
    #Should never get here because of AcceptsMethods decerator
    return HttpResponse(status=405)
Ejemplo n.º 7
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')


  #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)
  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 as e:
        return HttpResponseBadRequest('Location not found. Geocoder error: ' + str(e))
    else:
      return HttpResponseBadRequest('Bad location')

  return HttpJSONResponse(json.dumps(newPlayer, cls=UDJEncoder), status=201)
Ejemplo n.º 8
0
 def wrapper(*args, **kwargs):
     toReturn = function(*args, **kwargs)
     request = args[0]
     user = getUserForTicket(request)
     player = kwargs['player']
     if user != player.owning_user:
         participant = Participant.objects.get(user=user, player=player)
         participant.time_last_interaction = datetime.now()
         participant.save()
     return toReturn
Ejemplo n.º 9
0
def getFavorites(request, player_id):
  try:
    player = Player.objects.get(pk=player_id)
  except ObjectDoesNotExist:
    toReturn = HttpResponseNotFound()
    toReturn[MISSING_RESOURCE_HEADER] = 'player'
    return toReturn
  user = getUserForTicket(request)
  favorites = Favorite.objects.filter(user=user, favorite_song__library=player.DefaultLibrary)
  return HttpJSONResponse(json.dumps(favorites, cls=UDJEncoder))
Ejemplo n.º 10
0
 def wrapper(*args, **kwargs):
   toReturn = function(*args, **kwargs)
   request = args[0]
   user = getUserForTicket(request)
   player = kwargs['player']
   if user != player.owning_user:
     participant = Participant.objects.get(user=user, player=player)
     participant.time_last_interaction = datetime.now()
     participant.save()
   return toReturn
Ejemplo n.º 11
0
def logoutOfPlayer(request, player_id, player):
  user = getUserForTicket(request)

  try:
    toLogOut = Participant.objects.get(player=player, user=user)
    toLogOut.logout_flag = True
    toLogOut.save()
  except ObjectDoesNotExist:
    toReturn = HttpResponseNotFound()
    toReturn[MISSING_RESOURCE_HEADER] = 'user'
    return toReturn

  return HttpResponse()
Ejemplo n.º 12
0
def logoutOfPlayer(request, player_id, player):
    user = getUserForTicket(request)

    try:
        toLogOut = Participant.objects.get(player=player, user=user)
        toLogOut.logout_flag = True
        toLogOut.save()
    except ObjectDoesNotExist:
        toReturn = HttpResponseNotFound()
        toReturn[MISSING_RESOURCE_HEADER] = 'user'
        return toReturn

    return HttpResponse()
Ejemplo n.º 13
0
 def wrapper(*args, **kwargs):
   request = args[0]
   user = getUserForTicket(request)
   player = kwargs['player']
   if player.owning_user==user or player.isActiveParticipant(user):
     return function(*args, **kwargs)
   elif player.isKicked(user):
     toReturn = HttpResponse(status=401)
     toReturn['WWW-Authenticate'] = 'kicked'
     return toReturn
   else:
     toReturn = HttpResponse(status=401)
     toReturn['WWW-Authenticate'] = 'begin-participating'
     return toReturn
Ejemplo n.º 14
0
def participateWithPlayer(request, player_id, player):

  def onSuccessfulPlayerAuth(activePlayer, user):
    #very important to check if they're banned or player is full first.
    #otherwise we might might mark them as actually participating
    if Participant.objects.filter(user=user, player=activePlayer, ban_flag=True).exists():
      toReturn = HttpResponseForbidden()
      toReturn[FORBIDDEN_REASON_HEADER] = 'banned'
      return toReturn
    if activePlayer.isFull():
      toReturn = HttpResponseForbidden()
      toReturn[FORBIDDEN_REASON_HEADER] = 'player-full'
      return toReturn

    obj, created = Participant.objects.get_or_create(player=activePlayer, user=user)
    if not created:
      obj.time_last_interation = datetime.now()
      obj.kick_flag = False
      obj.logout_flag = False
      obj.save()

    return HttpResponse(status=201)


  user = getUserForTicket(request)
  playerPassword = PlayerPassword.objects.filter(player=player)
  if playerPassword.exists():
    hashedPassword = ""
    if not request.META.has_key('CONTENT_TYPE'):
      return HttpResponseBadRequest("must specify content type")
    elif request.META['CONTENT_TYPE'] != 'text/json':
      return HttpResponse("must send json", status=415)
    elif request.raw_post_data == '':
      return HttpResponseBadRequest("Bad JSON")
    try:
      password_json = json.loads(request.raw_post_data)
      password = password_json['password']
      hashedPassword = hashPlayerPassword(password)
    except ValueError:
      return HttpResponseBadRequest('Bad JSON')

    if hashedPassword == playerPassword[0].password_hash:
      return onSuccessfulPlayerAuth(player, user)


    toReturn = HttpResponse(status=401)
    toReturn['WWW-Authenticate'] = 'player-password'
    return toReturn
  else:
    return onSuccessfulPlayerAuth(player, user)
Ejemplo n.º 15
0
def createSongSet(request, player_id, player):
  user = getUserForTicket(request)

  try:
    songSetJSON = json.loads(request.raw_post_data)
    if 'name' not in songSetJSON or 'description' not in songSetJSON or 'date_created' not in songSetJSON:
      return HttpResponseBadRequest('Bad JSON')
  except ValueError:
    return HttpResponseBadRequest('Bad JSON')

  if player.Songsets().filter(name=songSetJSON['name']).exclude(description=songSetJSON['description'], date_created=songSetJSON['date_created']).exists():
    return HttpResponse('duplicate song set', status=409)


  newSongSet = SongSet(player, songSetJSON['name'], ['desciption'], user, songSetJSON['date_created'])

  newSongSet.save()
  return HttpResonse(status=201)
Ejemplo n.º 16
0
def participateWithPlayer(request, player_id, player):
    def onSuccessfulPlayerAuth(activePlayer, user):
        #very important to check if they're banned or player is full first.
        #otherwise we might might mark them as actually participating
        if Participant.objects.filter(user=user,
                                      player=activePlayer,
                                      ban_flag=True).exists():
            toReturn = HttpResponseForbidden()
            toReturn[FORBIDDEN_REASON_HEADER] = 'banned'
            return toReturn
        if activePlayer.isFull():
            toReturn = HttpResponseForbidden()
            toReturn[FORBIDDEN_REASON_HEADER] = 'player-full'
            return toReturn

        obj, created = Participant.objects.get_or_create(player=activePlayer,
                                                         user=user)
        if not created:
            obj.time_last_interation = datetime.now()
            obj.kick_flag = False
            obj.logout_flag = False
            obj.save()

        return HttpResponse(status=201)

    user = getUserForTicket(request)
    playerPassword = PlayerPassword.objects.filter(player=player)
    if playerPassword.exists():
        if DJANGO_PLAYER_PASSWORD_HEADER in request.META:
            hashedPassword = hashPlayerPassword(
                request.META[DJANGO_PLAYER_PASSWORD_HEADER])
            if hashedPassword == playerPassword[0].password_hash:
                return onSuccessfulPlayerAuth(player, user)

        toReturn = HttpResponse(status=401)
        toReturn['WWW-Authenticate'] = 'player-password'
        return toReturn
    else:
        return onSuccessfulPlayerAuth(player, user)
Ejemplo n.º 17
0
def participateWithPlayer(request, player_id, player):

  def onSuccessfulPlayerAuth(activePlayer, user):
    #very important to check if they're banned or player is full first.
    #otherwise we might might mark them as actually participating
    if Participant.objects.filter(user=user, player=activePlayer, ban_flag=True).exists():
      toReturn = HttpResponseForbidden()
      toReturn[FORBIDDEN_REASON_HEADER] = 'banned'
      return toReturn
    if activePlayer.isFull():
      toReturn = HttpResponseForbidden()
      toReturn[FORBIDDEN_REASON_HEADER] = 'player-full'
      return toReturn

    obj, created = Participant.objects.get_or_create(player=activePlayer, user=user)
    if not created:
      obj.time_last_interation = datetime.now()
      obj.kick_flag = False
      obj.logout_flag = False
      obj.save()

    return HttpResponse(status=201)


  user = getUserForTicket(request)
  playerPassword = PlayerPassword.objects.filter(player=player)
  if playerPassword.exists():
    if DJANGO_PLAYER_PASSWORD_HEADER in request.META:
      hashedPassword = hashPlayerPassword(request.META[DJANGO_PLAYER_PASSWORD_HEADER])
      if hashedPassword == playerPassword[0].password_hash:
        return onSuccessfulPlayerAuth(player, user)

    toReturn = HttpResponse(status=401)
    toReturn['WWW-Authenticate'] = 'player-password'
    return toReturn
  else:
    return onSuccessfulPlayerAuth(player, user)
Ejemplo n.º 18
0
def multiModActivePlaylist(request, player):
  player.lockActivePlaylist()
  try:
    toAdd = json.loads(request.POST['to_add'])
    toRemove = json.loads(request.POST['to_remove'])
  except ValueError:
    return HttpResponseBadRequest('Bad JSON\n. Couldn\'t even parse.\n Given data:' + request.raw_post_data)

  user = getUserForTicket(request)
  #Only admins and owners may remove songs from the playlist
  if len(toRemove) != 0 and not (player.isAdmin(user) or player.owning_user==user):
    return HttpResponseForbidden()

  try:
    #0. lock active playlist
    player.lockActivePlaylist()

    #first, validate/process all our inputs
    # 1. Ensure none of the songs to be deleted aren't on the playlist
    notOnPlaylist = getNotOnPlaylist(toRemove, player)
    if len(notOnPlaylist) > 0:
      toReturn = HttpJSONResponse(json.dumps(notOnPlaylist), status=404)
      toReturn[MISSING_RESOURCE_HEADER] = 'song'
      return toReturn

    # 2. Ensure all of the songs to be added actually exists in the library
    notInLibrary = []
    for songId in toAdd:
      if not LibraryEntry.songExsits(songId, player):
        notInLibrary.append(songId)

    if len(notInLibrary) > 0:
      toReturn = HttpJSONResponse(json.dumps(notInLibrary), content_type="text/json", status=404)
      toReturn[MISSING_RESOURCE_HEADER] = 'song'
      return toReturn

    # 3. See if there are any songs that we're trying to add that are already on the playlist
    # and vote them up instead.
    alreadyOnPlaylist = getAlreadyOnPlaylist(toAdd, player)
    toAdd = filter(lambda x: x not in alreadyOnPlaylist, toAdd)
    try:
      currentSong = ActivePlaylistEntry.objects.get(song__player=player, state='PL')
    except ObjectDoesNotExist:
      currentSong = None
    for libid in alreadyOnPlaylist:
      #make sure we don't vote on the currently playing song
      if currentSong != None and currentSong.song.player_lib_song_id != libid:
        voteSong(player, user, libid, 1)

    #alright, should be good to go. Let's actually add/remove songs
    #Note that we didn't make any actual changes to the DB until we were sure all of our inputs
    #were good and we weren't going to return an error HttpResponse. This is what allows us to use
    #the commit on success
    addSongsToPlaylist(toAdd, player, user)
    removeSongsFromPlaylist(toRemove, player, user)
  except ValueError:
    return HttpResponseBadRequest('Bad JSON\n' + 'toAdd: ' + str(toAdd) + '\ntoRemove: ' + str(toRemove))
  except TypeError:
    return HttpResponseBadRequest('Bad JSON\n' + 'toAdd: ' + str(toAdd) + '\ntoRemove: ' + str(toRemove))


  return HttpResponse()
Ejemplo n.º 19
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))
Ejemplo n.º 20
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)
Ejemplo n.º 21
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')


  #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)
  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 as e:
        return HttpResponseBadRequest('Location not found. Geocoder error: ' + str(e))
    else:
      return HttpResponseBadRequest('Bad location')

  #create default library for new player
  new_library = Library(name="Default library", description="default library", pub_key="")
  new_library.save()
  new_default = DefaultLibrary(library=new_library, player=newPlayer)
  new_default.save()
  new_owned = OwnedLibrary(library=new_library, owner=user)
  new_owned.save()
  new_associated = AssociatedLibrary(library=new_library, player=newPlayer)
  new_associated.save()

  #Create Owner Permissions Group
  owner_group = PlayerPermissionGroup(player=newPlayer, name="owner")
  owner_group.save()
  owner_group.add_member(user)

  #Create Admin Permissions Group
  admin_group = PlayerPermissionGroup(player=newPlayer, name="admin")
  admin_group.save()

  #Add owner_group and admin group to select permissions
  set_default_player_permissions(newPlayer, owner_group)
  set_default_player_permissions(newPlayer, admin_group)

  return HttpJSONResponse(json.dumps(newPlayer, cls=UDJEncoder), status=201)
Ejemplo n.º 22
0
def voteSongUp(request, player_id, lib_id, player):
  return voteSong(player, getUserForTicket(request), lib_id, 1)