Пример #1
0
 def get_error_message_player_stat(self, stat, player):
     """get a error message when the attribute is not a correct type"""
     message = Message(f"error", f"{stat} of {player} is not of type float")
     json_rep = json.dumps({'message': message.repr_json()},
                           cls=ComplexEncoder)
     json_rep = json.loads(json_rep)
     return json_rep
Пример #2
0
def check_user_data_request(data):
    """helper method to check if the right data is sent"""
    if 'username' not in data or 'email' not in data or 'password' not in data:
        message = Message("error", f"No username or password or email sent")
        return False, create_response({"message": message.repr_json()}, status.HTTP_400_BAD_REQUEST)
    else:
        return True, ""
Пример #3
0
 def get(self, request):
     """return all upcoming matches. Matches need to start later than now"""
     check, json_message, response_status = check_authorization(request)
     if check:
         message = Message("success", f"CSGO Upcoming Matches")
         upcoming_matches = Match.objects.filter(
             date__range=(datetime.now(), datetime.now() +
                          timedelta(days=15))).order_by("date")
         upcoming_matches = MatchSerializer(upcoming_matches,
                                            context={
                                                'request': request
                                            },
                                            many=True).data
         for match in upcoming_matches:
             match.update({
                 "nnPickedTeam":
                 match["Team_1"]["name"]
                 if match["team_1_confidence"] >= match["team_2_confidence"]
                 else match["Team_2"]["name"]
             })
             match.update({
                 "svmPickedTeam":
                 match["Team_1"]["name"] if float(match["prediction_svm"])
                 == 0 else match["Team_2"]["name"]
             })
         json_rep = json.dumps(
             {
                 'message': message.repr_json(),
                 'upcoming_matches': upcoming_matches
             },
             cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return Response(json_rep, status=response_status)
     else:
         return Response(json_message, status=response_status)
Пример #4
0
def check_authorization_in_header(request):
    """helping method for checking the authorization"""
    # check if the authorization token is sent in the headers
    if "Authorization" not in request.headers:
        message = Message("error", f"No authorization token sent")
        return False, create_response({'message': message.repr_json()}, status.HTTP_401_UNAUTHORIZED)
    else:
        return True, ""
Пример #5
0
 def get_error_message_player_stat_in_range(self, stat, player, range_1,
                                            range_2):
     """get a error message when the stat is not in the correct value range"""
     message = Message(
         f"error",
         f"{stat} of {player} is not in range {range_1} and {range_2}")
     json_rep = json.dumps({'message': message.repr_json()},
                           cls=ComplexEncoder)
     json_rep = json.loads(json_rep)
     return json_rep
Пример #6
0
 def post(self, request):
     """Method updates a user"""
     check_authorization, response = check_authorization_in_header(request)
     if not check_authorization:
         return response
     data = json.loads(request.body or "{}")
     check_data, response = check_user_data_request(data)
     if not check_data:
         return response
     user = check_user(request)
     if user is not None:
         serialized_user = UserSerializer(data=data)
         # validate the user and make sure that the user exists error is ignored when the username is the same as in
         # the authentication
         if serialized_user.is_valid() or str(user.user) == str(data['username']):
             # update user
             user = User.objects.get(username=user.user)
             user.username = data['username']
             user.set_password(data['password'])
             user.email = data['email']
             user.save()
             # create or get user just in case
             token, created = Token.objects.get_or_create(user=user)
             user = UserSerializer(user).data
             message = Message("success", f"Successfully updated account: {data['username']}")
             return create_response({"message": message.repr_json(), "token": token.key, 'user': user},
                                    status.HTTP_200_OK)
         else:
             message = Message("error", "")
             for error in serialized_user.errors:
                 message.message += serialized_user.errors[error][0] + "\n"
             return create_response({"message": message.repr_json()}, status.HTTP_400_BAD_REQUEST)
     else:
         message = Message("error", f"Authentication failed")
         return create_response({"message": message.repr_json()}, status.HTTP_401_UNAUTHORIZED)
Пример #7
0
 def check_teams(self, data):
     """checks if a team is in the data sent"""
     if "team_1" not in data or "team_2" not in data:
         message = Message("error", f"No teams sent")
         json_rep = json.dumps({'message': message.repr_json()},
                               cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return False, Response(json_rep,
                                status=status.HTTP_400_BAD_REQUEST)
     else:
         return True, ""
Пример #8
0
 def check_players_in_team(self, data, team):
     """checks if players are sent in the data"""
     if "Player_1" not in data[team] or "Player_2" not in data[
             team] or "Player_3" not in data[team] or "Player_4" not in data[
                 team] or "Player_5" not in data[team]:
         message = Message(f"error", f"No player for {team} sent")
         json_rep = json.dumps({'message': message.repr_json()},
                               cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return False, Response(json_rep,
                                status=status.HTTP_400_BAD_REQUEST)
     else:
         return True, ""
Пример #9
0
 def check_players(self, data):
     """checks if the players has the right attributes in the data sent"""
     team_list = ["team_1", "team_2"]
     player_list = [
         "Player_1", "Player_2", "Player_3", "Player_4", "Player_5"
     ]
     for team in team_list:
         for player in player_list:
             if "adr" not in data[team][player] or "dpr" not in data[team][
                     player] or "kast" not in data[team][
                         player] or "impact" not in data[team][
                             player] or "kpr" not in data[team][player]:
                 message = Message(f"error",
                                   f"No stats sent for {player} in {team}")
                 json_rep = json.dumps({'message': message.repr_json()},
                                       cls=ComplexEncoder)
                 json_rep = json.loads(json_rep)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             else:
                 return True, ""
Пример #10
0
 def get(self, request):
     """return all teams"""
     check, json_message, response_status = check_authorization(request)
     if check:
         message = Message("success", f"Here are the teams")
         teams = Team.objects.all().order_by("end_date")
         team_set = list({team.name: team for team in teams}.values())
         team_set.sort(key=lambda x: x.name)
         teams = TeamsPredictionSerializer(team_set,
                                           context={
                                               'request': request
                                           },
                                           many=True).data
         json_rep = json.dumps(
             {
                 'message': message.repr_json(),
                 'teams': teams
             },
             cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return Response(json_rep, status=response_status)
     else:
         return Response(json_message, status=response_status)
Пример #11
0
    def post(self, request):
        """method log in the user and returns a user object with a token"""
        data = json.loads(request.body or "{}")
        # check correctness of body
        if 'username' not in data or 'password' not in data:
            message = Message("error", f"No username or password sent")
            return create_response({"message": message.repr_json()}, status.HTTP_400_BAD_REQUEST)

        username = data['username']
        password = data['password']
        user = authenticate(request, username=username, password=password)
        # check if user exists
        if user is not None:
            # get or generate token for authentication later
            token, created = Token.objects.get_or_create(user=user)
            message = Message("success", f"Successfully logged in: {data['username']}")
            user = User.objects.get(username=username)
            user = UserSerializer(user).data
            # return message, token and user information
            return create_response({"message": message.repr_json(), "token": token.key, 'user': user},
                                   status.HTTP_200_OK)
        else:
            message = Message("error", f"Either Username or Password is wrong")
            return create_response({"message": message.repr_json()}, status.HTTP_200_OK)
Пример #12
0
 def get(self, request):
     """Method authenticate the user. Checks if he is logged in"""
     check_authorization, response = check_authorization_in_header(request)
     if not check_authorization:
         return response
     user = check_user(request)
     message = Message("success", f"Yes still authenticated")
     if user is None:
         message = Message("error", f"No user matches the sent token")
         return create_response({'message': message.repr_json()}, status.HTTP_401_UNAUTHORIZED)
     else:
         user_name = Token.objects.get(key=request.headers.get('Authorization')).user
         user = User.objects.get(username=user_name)
         user = UserSerializer(user).data
         return create_response({'message': message.repr_json(), 'user': user}, status.HTTP_200_OK)
Пример #13
0
 def post(self, request):
     """method logout the user by deleting his token"""
     # check if token is in the header
     check_authorization, response = check_authorization_in_header(request)
     if not check_authorization:
         return response
     # logging out is basically deleting the token for the user
     user = check_user(request)
     message = Message("success", f"Successfully logged out")
     if user is None:
         message = Message("error", f"Can´t logout since nobody is logged in")
         return create_response({'message': message.repr_json()}, status.HTTP_401_UNAUTHORIZED)
     else:
         Token.objects.get(key=request.headers.get('Authorization')).delete()
         return create_response({'message': message.repr_json()}, status.HTTP_200_OK)
Пример #14
0
 def get(self, request, id):
     """return the team given by an id"""
     check, json_message, response_status = check_authorization(request)
     if check:
         message = Message("success", f"Here is the Team")
         team = Team.objects.filter(id=id)
         if not team.exists():
             message = Message("error", f"No team found")
             json_rep = json.dumps({'message': message.repr_json()},
                                   cls=ComplexEncoder)
             return Response(json_rep, status=response_status)
         team = team.first()
         team = TeamSerializer(team, context={'request': request}).data
         json_rep = json.dumps(
             {
                 'message': message.repr_json(),
                 'team': team
             },
             cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return Response(json_rep, status=response_status)
     else:
         return Response(json_message, status=response_status)
Пример #15
0
def check_authorization(request):
    permissions = Permission.objects.filter(name__in=[
        "Can view match result", "Can view player", "Can view team",
        "Can view match"
    ])
    if "Authorization" not in request.headers:
        message = Message("error", f"No authorization token sent")
        json_rep = json.dumps({'message': message.repr_json()},
                              cls=ComplexEncoder)
        json_rep = json.loads(json_rep)
        return False, json_rep, status.HTTP_401_UNAUTHORIZED
    user = None
    try:
        user = Token.objects.get(key=request.headers.get('Authorization'))
    except Token.DoesNotExist:
        pass
    if user is None:
        message = Message("error", f"No user matches the sent token")
        json_rep = json.dumps({'message': message.repr_json()},
                              cls=ComplexEncoder)
        json_rep = json.loads(json_rep)
        return False, json_rep, status.HTTP_401_UNAUTHORIZED
    else:
        user_name = user.user
        user = User.objects.get(username=user_name)
        if not user.has_perms(permissions):
            message = Message("error", f"No permissions")
            json_rep = json.dumps({'message': message.repr_json()},
                                  cls=ComplexEncoder)
            json_rep = json.loads(json_rep)
            return False, json_rep, status.HTTP_403_FORBIDDEN
        message = Message("success", f"Here is the data")
        json_rep = json.dumps({'message': message.repr_json()},
                              cls=ComplexEncoder)
        json_rep = json.loads(json_rep)
        return True, json_rep, status.HTTP_200_OK
Пример #16
0
 def delete(self, request, id):
     """method deletes a user given by his id"""
     # check authorization
     check_authorization, response = check_authorization_in_header(request)
     if not check_authorization:
         return response
     staff_member = check_user(request)
     if staff_member is None:
         message = Message("error", f"Not authenticated")
         return create_response({'message': message.repr_json()}, status.HTTP_401_UNAUTHORIZED)
     else:
         # check permission to delete a user
         staff_name = Token.objects.get(key=request.headers.get('Authorization')).user
         staff_member = User.objects.get(username=staff_name)
         permission = Permission.objects.get(name="Can delete user")
         if not staff_member.has_perm(permission):
             message = Message("error", f"No permission")
             return create_response({'message': message.repr_json()}, status.HTTP_403_FORBIDDEN)
         else:
             delete_user = User.objects.filter(id=id)
             if len(delete_user) == 0:
                 message = Message("error", f"User does not exist")
                 return create_response({'message': message.repr_json()}, status.HTTP_400_BAD_REQUEST)
             else:
                 delete_user = delete_user.first()
                 token, _ = Token.objects.get_or_create(user=delete_user)
                 Token.objects.get(key=token).delete()
                 delete_user.delete()
                 message = Message("success", f"Successfully deleted account {id}")
                 return create_response({'message': message.repr_json()}, status.HTTP_200_OK)
Пример #17
0
 def validate_data(self, data):
     """check if the data attributes are in the correct value range"""
     team_list = ["team_1", "team_2"]
     player_list = [
         "Player_1", "Player_2", "Player_3", "Player_4", "Player_5"
     ]
     for team in team_list:
         try:
             float(data[team]["winning_percentage"])
         except:
             message = Message(
                 f"error",
                 f"Winning percentage of {team} is not of type float")
             json_rep = json.dumps({'message': message.repr_json()},
                                   cls=ComplexEncoder)
             json_rep = json.loads(json_rep)
             return False, Response(json_rep,
                                    status=status.HTTP_400_BAD_REQUEST)
         if 0 <= float(data[team]["winning_percentage"]) <= 1:
             pass
         else:
             message = Message(
                 f"error",
                 f"Winning percentage of {team} is not between 0 and 1")
             json_rep = json.dumps({'message': message.repr_json()},
                                   cls=ComplexEncoder)
             json_rep = json.loads(json_rep)
             return False, Response(json_rep,
                                    status=status.HTTP_400_BAD_REQUEST)
         for player in player_list:
             try:
                 float(data[team][player]["adr"])
             except:
                 json_rep = self.get_error_message_player_stat(
                     "adr", player)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             try:
                 float(data[team][player]["dpr"])
             except:
                 json_rep = self.get_error_message_player_stat(
                     "dpr", player)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             try:
                 float(data[team][player]["kast"])
             except:
                 json_rep = self.get_error_message_player_stat(
                     "kast", player)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             try:
                 float(data[team][player]["impact"])
             except:
                 json_rep = self.get_error_message_player_stat(
                     "impact", player)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             try:
                 float(data[team][player]["kpr"])
             except:
                 json_rep = self.get_error_message_player_stat(
                     "kpr", player)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             if 0 <= float(data[team][player]["adr"]) <= 1000:
                 pass
             else:
                 json_rep = self.get_error_message_player_stat_in_range(
                     "adr", player, 0, 1000)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             if 0 <= float(data[team][player]["dpr"]) <= 1:
                 pass
             else:
                 json_rep = self.get_error_message_player_stat_in_range(
                     "dpr", player, 0, 1)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             if 0 <= float(data[team][player]["kast"]) <= 10:
                 pass
             else:
                 json_rep = self.get_error_message_player_stat_in_range(
                     "kast", player, 0, 10)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             if 0 <= float(data[team][player]["impact"]) <= 5:
                 pass
             else:
                 json_rep = self.get_error_message_player_stat_in_range(
                     "impact", player, 0, 5)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
             if 0 <= float(data[team][player]["kpr"]) <= 10:
                 pass
             else:
                 json_rep = self.get_error_message_player_stat_in_range(
                     "kpr", player, 0, 10)
                 return False, Response(json_rep,
                                        status=status.HTTP_400_BAD_REQUEST)
     return True, ""
Пример #18
0
    def post(self, request):
        """method register a new user"""
        check_authorization, response = check_authorization_in_header(request)
        if not check_authorization:
            return response
        data = json.loads(request.body or "{}")

        # check if right data was sent
        check_data, response = check_user_data_request(data)
        if not check_data:
            return response
        # check if the user who want to create a new user is logged in
        staff_member = check_user(request)
        if staff_member is None:
            message = Message("error", f"Not authenticated")
            return create_response({'message': message.repr_json()}, status.HTTP_401_UNAUTHORIZED)
        else:
            # check if the user who want to create a new user has the permission to do so
            permission = Permission.objects.get(name="Can add user")
            staff_name = Token.objects.get(key=request.headers.get('Authorization')).user
            staff_user = User.objects.get(username=staff_name)
            if not staff_user.has_perm(permission):
                message = Message("error", f"No permission")
                return create_response({'message': message.repr_json()}, status.HTTP_403_FORBIDDEN)
            else:
                # validate user
                serialized_user = UserSerializer(data=data)
                if serialized_user.is_valid():
                    # create user
                    user = User.objects.create_user(username=data['username'],
                                                    email=data['email'],
                                                    password=data['password'])
                    # token, created = Token.objects.get_or_create(user=user)
                    # user = UserSerializer(user).data
                    # message = Message("success", f"Welcome {data['username']}")
                    # return create_response({"message": message.repr_json(), "token": token.key, 'user': user},
                    #                        status.HTTP_200_OK)
                    message = Message("success", f"User {data['username']} successful created")
                    return create_response({"message": message.repr_json()}, status.HTTP_200_OK)
                else:
                    message = Message("error", "")
                    for error in serialized_user.errors:
                        message.message += serialized_user.errors[error][0] + "\n"
                    return create_response({"message": message.repr_json()}, status.HTTP_400_BAD_REQUEST)
Пример #19
0
    def post(self, request):
        """make a prediction on two given teams"""
        check, json_message, response_status = check_authorization(request)
        if check:
            data = json.loads(request.body or "{}")
            # check if the teams are correct
            check_teams, response = self.check_teams(data)
            if not check_teams:
                return response
            # check if the players are correct
            check_player_team_1, response = self.check_players_in_team(
                data, "team_1")
            if not check_player_team_1:
                return response
            check_player_team_2, response = self.check_players_in_team(
                data, "team_1")
            if not check_player_team_2:
                return response
            # check if a single player is correct
            check_players, response = self.check_players(data)
            if not check_players:
                return response
            # check if the values are correct
            validate_data, response = self.validate_data(data)
            if not validate_data:
                return response

            message = Message("success", f"Prediction")
            # create a prediction array and make a prediction
            prediction_array = np.array(
                [[data["team_1"]["winning_percentage"]]])
            prediction_array = np.concatenate(
                (prediction_array,
                 self.get_team_player_array(
                     data["team_1"]["Player_1"], data["team_1"]["Player_2"],
                     data["team_1"]["Player_3"], data["team_1"]["Player_4"],
                     data["team_1"]["Player_5"])),
                axis=1)
            prediction_array = np.concatenate(
                (prediction_array,
                 np.array([[data["team_2"]["winning_percentage"]]])),
                axis=1)
            prediction_array = np.concatenate(
                (prediction_array,
                 self.get_team_player_array(
                     data["team_2"]["Player_1"], data["team_2"]["Player_2"],
                     data["team_2"]["Player_3"], data["team_2"]["Player_4"],
                     data["team_2"]["Player_5"])),
                axis=1)
            # if data["mode"] == "BO1":
            #     prediction_model = settings.PREDICTION_MODEL_ALL_WINS
            #     prediction_model_svm = settings.PREDICTION_MODEL_SVM_ALL_WINS
            # else:
            #     prediction_model = settings.PREDICTION_MODEL_BO3_WINS
            #     prediction_model_svm = settings.PREDICTION_MODEL_SVM_BO3_WINS
            # get the right model
            prediction_model = settings.PREDICTION_MODEL_ALL_WINS
            prediction_model_svm = settings.PREDICTION_MODEL_SVM_ALL_WINS

            prediction_svm = prediction_model_svm.predict(prediction_array)
            team_2_confidence = round(
                prediction_model.predict(prediction_array)[0][0], 4)
            team_1_confidence = round(1 - team_2_confidence, 4)
            team_1_confidence = team_1_confidence.item()
            team_2_confidence = team_2_confidence.item()
            team_2_confidence = round(team_2_confidence, 4)
            team_1_confidence = round(team_1_confidence, 4)
            json_rep = json.dumps(
                {
                    'message': message.repr_json(),
                    'prediction': {
                        "team_1_confidence": team_1_confidence,
                        "team_2_confidence": team_2_confidence,
                        "prediction_svm": prediction_svm[0]
                    }
                },
                cls=ComplexEncoder)
            json_rep = json.loads(json_rep)
            return Response(json_rep, status=response_status)
        else:
            return Response(json_message, status=response_status)