Пример #1
0
    def handle(self, *args, **options):

        lor_watcher = LorWatcher(api_key=settings.RIOT_API_KEY)

        with open('match_ids.json', 'r') as f:
            match_ids = json.load(f)

        i = 0

        while i < len(match_ids):
            match_id = match_ids[i]
            try:
                match = Match.objects.get(match_id=match_id)
                i += 1
            except Match.DoesNotExist as e:
                print(f"Generating match for match id {match_id}")

                try:
                    match_results = lor_watcher.match.by_id(region="americas",
                                                            match_id=match_id)
                    Match.create(match_results)
                    i += 1
                except HTTPError as e:
                    status_code = e.response.status_code
                    if status_code == 429:
                        print("Too many requests, waiting for 10 minutes")
                        sleep(600)
                    else:
                        print(f"Error code {status_code}")

                sleep(1)
Пример #2
0
class TestMatchSerializer(TestCase):
    def setUp(self):
        self.characters = [
            Character(name='Test1', role=Character.DAMAGE),
            Character(name='Test2', role=Character.DAMAGE)
        ]
        for c in self.characters:
            c.save()

        self.user = User.objects.create_user('testuser')

        self.match = Match(user=self.user, mmr_after=1000)
        self.match.save()
        self.match.characters.set(self.characters)
    
    def testSerializingMatch(self):
        # Test if match serialization works correctly
        expected_data = {
            'id': self.match.id,
            'characters': [c.id for c in self.match.characters.all()],
            'date': DateTimeField().to_representation(self.match.date),
            'mmr_after': self.match.mmr_after
        }
        serializer = MatchSerializer(self.match)
        self.assertEqual(
            expected_data,
            serializer.data,
            'Serializer should return data in expected format'
        )
Пример #3
0
class TestIsOwnerPermission(TestCase):
    def setUp(self):
        self.character = Character(name='Test', role=Character.DAMAGE)
        self.character.save()

        self.owner = User.objects.create_user('owner')
        self.notOwner = User.objects.create_user('notowner')

        self.match = Match(user=self.owner, mmr_after=1000)
        self.match.save()
        self.match.characters.set([self.character])

        self.permission = IsMatchOwner()

    def testPermissionGrantedToOwner(self):
        """
        If user currently logged in is owner of match, permission should
        be granted, both for safe (GET) and unsafe (e. g. POST) methods
        """
        factory = APIRequestFactory()
        get_request = factory.get('/path_does_not_matter_here/')
        force_authenticate(get_request, user=self.owner)
        get_request.user = self.owner # there is no .user in request generated by APIRequestFactory
        self.assertTrue(
            self.permission.has_object_permission(get_request, None, self.match),
            'Permission should be granted for GET request with user which is match owner'
        )

        post_request = factory.post('/path_does_not_matter_here/')
        force_authenticate(post_request, user=self.owner)
        post_request.user = self.owner # there is no .user in request generated by APIRequestFactory
        self.assertTrue(
            self.permission.has_object_permission(post_request, None, self.match),
            'Permission should be granted for unsafe (e.g. POST) request with user which is match owner'
        )
    
    def testPermissionDeniedToNotOwner(self):
        """
        If user currently logged in is not owner of match, permission should
        be denied, both for safe (GET) and unsafe (e. g. POST) methods
        """
        factory = APIRequestFactory()
        get_request = factory.get('/path_does_not_matter_here/')
        force_authenticate(get_request, user=self.notOwner)
        get_request.user = self.notOwner # there is no .user in request generated by APIRequestFactory
        self.assertFalse(
            self.permission.has_object_permission(get_request, None, self.match),
            'Permission should be denied for GET request with user which is not match owner'
        )

        post_request = factory.post('/path_does_not_matter_here/')
        force_authenticate(post_request, user=self.notOwner)
        post_request.user = self.notOwner # there is no .user in request generated by APIRequestFactory
        self.assertFalse(
            self.permission.has_object_permission(post_request, None, self.match),
            'Permission should be denied for unsafe (e.g. POST) request with user which is not match owner'
        )
Пример #4
0
    def post(self, request, pk):
        form = WagerChallengeForm(request.POST, user=request.user)
        myrequest = WagerRequest.objects.get(pk=pk)
        challenge = form.instance
        challenge.creator = self.request.user
        if form.is_valid():
            challenger = UserProfile.objects.get(
                user__username=challenge.creator)
            if challenger.credits < myrequest.credits:
                messages.error(
                    self.request,
                    "You do not have enough credits in your account to challenge this team"
                )
                return redirect('wagers:list')
            if challenge.team == myrequest.team:
                messages.error(self.request,
                               "A team cannot challenge it's own wager")
                return redirect('wagers:list')
            for y in challenge.team.players.all():
                for x in myrequest.team.players.all():
                    if x == y:
                        messages.error(
                            self.request,
                            "A player cannot be on both teams at the same time"
                        )
                        return redirect('wagers:list')
            challenge.save()
            myrequest.challenge_accepted = True
            myrequest.challenge = challenge
            myrequest.save()
            match = Match(type='w',
                          game=myrequest.game,
                          platform=myrequest.platform,
                          hometeam=myrequest.team,
                          awayteam=challenge.team,
                          bestof=myrequest.bestof,
                          teamformat=myrequest.teamformat,
                          info="Home Team: " + myrequest.info + "\n" +
                          "Away Team: " + challenge.info)
            match.save()
            wmatch = WagerMatch(match=match, credits=myrequest.credits)
            wmatch.save()
            myrequest.wmatch = wmatch
            myrequest.save()
            challenger.credits = challenger.credits - myrequest.credits
            challenge.save()
            myrequest.creator.credits = myrequest.creator.credits - myrequest.credits
            myrequest.save()
            messages.success(
                request,
                "Wager Challenge Created! You have 30 minutes to play your match and report the scores"
            )
            return redirect('wagers:match_detail', pk=wmatch.pk)

        messages.error(self.request,
                       "Something went wrong (this shouldn't be seen")
        return redirect('wagers:request_detail', pk=pk)
Пример #5
0
    def setUp(self):
        self.character = Character(name='Test', role=Character.DAMAGE)
        self.character.save()

        self.owner = User.objects.create_user('owner')
        self.notOwner = User.objects.create_user('notowner')

        self.match = Match(user=self.owner, mmr_after=1000)
        self.match.save()
        self.match.characters.set([self.character])

        self.permission = IsMatchOwner()
Пример #6
0
    def setUp(self):
        self.characters = [
            Character(name='Test1', role=Character.DAMAGE),
            Character(name='Test2', role=Character.DAMAGE)
        ]
        for c in self.characters:
            c.save()

        self.user = User.objects.create_user('testuser')

        self.match = Match(user=self.user, mmr_after=1000)
        self.match.save()
        self.match.characters.set(self.characters)
Пример #7
0
    def _generate_matches(self):
        """
        Create a match for each set of 2 players in the pool, and rounds to hold
        them
        """
        from matches.models import Match, Round

        rounds = {}
        players = [player for player in self.players.all()]

        if len(players) % 2 != 0: players.append(None)

        iterator = list(range(len(players)))
        for x in iterator:
            if x == 0: continue
            round = Round(pool=self, number=x)
            round.save()
            rounds[round] = []

        for x in iterator:
            if not players[x]: continue

            others_iterator = iterator.copy()
            others_iterator.remove(x)

            for y in others_iterator:
                if not players[y]: continue

                match_exists = Match.objects.filter(
                    player_1_init=players[x],
                    player_2_init=players[y]).exists()
                inverse_match_exists = Match.objects.filter(
                    player_1_init=players[y],
                    player_2_init=players[x]).exists()

                if match_exists or inverse_match_exists:
                    continue

                for scheduled_round, players_in_round in rounds.items():
                    if (players[x] not in players_in_round) and (
                            players[y] not in players_in_round):
                        break

                match = Match(player_1_init=players[x],
                              player_2_init=players[y],
                              round=scheduled_round,
                              round_index=0)
                match.save()
                rounds[scheduled_round] += [players[x], players[y]]
Пример #8
0
 def _create_two_person_match(self, order_num=None):
     m = Match(card=self.card)
     if order_num is not None:
         m.order = order_num
     m.save()
     m.add_competitor(self.w1)
     m.add_competitor(self.w2)
     m.save()
     return m
Пример #9
0
    def _generate_matches(self):
        """
        Create a match for each set of 2 players in the pool, and rounds to hold
        them
        """
        from matches.models import Match, Round

        rounds = {}
        players = [player for player in self.players.all()]

        if len(players) % 2 != 0: players.append(None)

        iterator = list(range(len(players)))
        for x in iterator:
            if x == 0: continue
            round = Round(pool=self, number=x)
            round.save()
            rounds[round] = []

        for x in iterator:
            if not players[x]: continue

            others_iterator = iterator.copy()
            others_iterator.remove(x)

            for y in others_iterator:
                if not players[y]: continue

                match_exists = Match.objects.filter(player_1_init=players[x], player_2_init=players[y]).exists()
                inverse_match_exists = Match.objects.filter(player_1_init=players[y], player_2_init=players[x]).exists()

                if match_exists or inverse_match_exists:
                    continue

                for scheduled_round, players_in_round in rounds.items():
                    if (players[x] not in players_in_round) and (players[y] not in players_in_round):
                        break

                match = Match(
                    player_1_init=players[x],
                    player_2_init=players[y],
                    round=scheduled_round,
                    round_index=0
                )
                match.save()
                rounds[scheduled_round] += [players[x], players[y]]
Пример #10
0
def load_matches(path):
    with open(path) as f:
        reader = csv.reader(f)
        bulk = []
        for row in reader:
            bulk.append(
                Match(home_team=row[1],
                      guest_team=row[2],
                      start_time=datetime.strptime(row[0], '%d/%m/%Y %H:%M')))
    Match.objects.bulk_create(bulk)
Пример #11
0
def upload_matches(matches):
    from matches.service.match_service import MatchService
    match_list = []
    logger.info('Match uploading started')
    for match in matches:
        if not Match.objects.filter(id=match['id']).exists():
            match_list.append(Match(**match))
    Match.objects.bulk_create(match_list)
    logger.info('Match uploading done')
    MatchService().clear_cache()
Пример #12
0
def monitor_player_games():

    try:
        match_ids = lor_watcher.match.by_puuid(region="americas", puuid=puuid)

        for match_id in match_ids:

            try:
                match = Match.objects.get(match_id=match_id)
            except Match.DoesNotExist as e:
                print(f"Generating match for match id {match_id}")

                match_results = lor_watcher.match.by_id(region="americas",
                                                        match_id=match_id)

                Match.create(match_results)
    except HTTPError as e:
        status_code = e.response.status_code
        if status_code == 403:
            print("API Key invalid!")
        else:
            print(f"API request errored with status code {status_code}")
Пример #13
0
def new_matches(match, index, tournament):
    new_match = Match()
    if match:
        new_match.next_match = match
    new_match.start_position = index
    new_match.turnaj = tournament
    index -= 1
    new_match.save()
    if index > 0:
        new_matches(new_match, index, tournament)
        new_matches(new_match, index, tournament)
Пример #14
0
 def create(self, data):
     """Create a match."""
     board = Match.create_board(data['width'], data['height'],
                                data['mines'])
     match = Match.objects.create(
         creator=data['creator'],
         board=board,
         mines=data['mines'],
         width=data['width'],
         height=data['height'],
         remaining_flags=data['mines'],
         remaining_free_cells=data['width'] * data['height'] -
         data['mines'])
     return match
Пример #15
0
    def setUp(self):
        self.match = Match.objects.create(
            match_id=1,
            home_team='Netherlands',
            guest_team='Russia',
            start_time='2008-06-21 19:45Z'
        )
        self.coef = Coefficient.objects.create(
            coef_ready=True,
            score={'0-0': 2, '1-0': 1.2, '1-1': 1.8, 'Any other score': 4},
            home_win=1.4,
            tie=2,
            guest_win=3.2,
            update_time='2008-06-10 00:00Z',
            match_id=Match(1)
        )
        self.prediction = Prediction.objects.create(
            home_score=4,
            guest_score=0,
            match_id=Match(1),
            submit_time='2008-06-20 20:00Z',
            user_id=1,

        )
Пример #16
0
    def get(self, request, *args, **kwargs):
        """
        this has an optional `uid` query parameter that filters the matches for the given user
        """
        uid = kwargs.get('uid', '')
        hydrate = request.GET.get('hydrate', False)
        match_list = Match.get_matches(uid=uid, state='match')
        response_json = []

        if uid and hydrate:
            response_json = self._hydrate_match_list(uid, match_list)
        else:
            response_json = [match.json() for match in match_list]

        return JsonResponse(response_json)
Пример #17
0
    def testMatchLogics(self):
        team1 = Team(short_name="SP", full_name="São Paulo FC")
        team2 = Team(short_name="Palmeiras", full_name="Palmeiras FC")
        team1.save()
        team2.save()

        season = Season(start_year=2012, end_year=2012)
        season.save()

        cp = Championship(name="Brasileirao", start_date=timezone.now())
        cp.season = season
        cp.save()

        match1 = Match()

        match1.championship = cp
        match1.home_team = team1
        match1.away_team = team2
        match1.match_date = timezone.now()

        match1.save()
Пример #18
0
def matchManager(request, id=None):
    if id:
        match = get_object_or_404(Match, pk=id)
    else:
        match = Match()
    if request.method == 'POST':
        form = MatchForm(request.POST, instance=match)
        if form.is_valid():
            form.save()
            return redirect(matchManager)
    form = MatchForm(instance=match)
    orphan_matches = Match.objects.filter(group=None, division=None)
    setup_matches = Match.objects.filter(server=None).exclude(is_setup=True)
    tournaments = Tournament.objects.all()
    context = {
        'orphan_matches': orphan_matches,
        'setup_matches': setup_matches,
        'tournaments': tournaments,
        'form': form,
    }
    return render(request, 'manager/manage_matches.html', context)
Пример #19
0
def match_list(request):

    match_date = gen_match_date()

    match_list = Match.objects.filter(match_date=match_date)

    if not match_list:  # download and save into database
        querysetlist=[]
        for data in downloader.get_match_list():
            kwargs = {k: v for k, v in data.items()}
            kwargs['match_date'] = match_date
            querysetlist.append(Match(**kwargs))
        Match.objects.bulk_create(querysetlist)

        # query again
        match_list = Match.objects.filter(match_date=match_date)

    content = {
            'match_list': match_list,
            }

    return render_to_response('match-list.html', RequestContext(request, content))
def raw_match_to_match_model(
    raw_match: Dict[Any, Any],
    raw_location_to_model_location: Dict[int, Location],
    raw_team_to_model_team: Dict[int, Team],
) -> Match:
    match_location = None
    if raw_match['Location']:
        external_location_id = raw_match['Location']['LocationID']
        match_location = raw_location_to_model_location[external_location_id]

    team1 = raw_team_to_model_team[raw_match['Team1']['TeamId']]
    team2 = raw_team_to_model_team[raw_match['Team2']['TeamId']]

    return Match(external_id=raw_match['MatchID'],
                 match_time_utc=raw_match['MatchDateTimeUTC'],
                 location=match_location,
                 matchday=raw_match['Group']['GroupOrderID'],
                 last_update_utc=western_europe_time_to_utc(
                     raw_match['LastUpdateDateTime']),
                 finished=raw_match['MatchIsFinished'],
                 team_1=team1,
                 team_2=team2)
Пример #21
0
    def generate_bracket(self):
        teams = len(self.teams.all())
        myteams = self.teams.all()
        self.current_round = 1
        self.save()
        round1 = SingleTournamentRound(tournament=self, roundnum=1)
        round1.save()
        if teams % 2 == 0:
            # no byes required - get 2 teams and make a match
            while len(myteams) != 0:
                temp1 = myteams.all().order_by("?").first()
                myteams.remove(temp1)
                myteams.save()
                temp2 = myteams.all().order_by("?").first()
                tempmatch = Match(awayteam=temp1, hometeam=temp2, maps=self.map_pool, game=self.game, platform=self.platform)
                tempmatch.save()
                myteams.remove(temp2)
                myteams.save()
                round1.matches.add(tempmatch)
                round1.save()

        else:
            # take the first team and give them a bye
            # TODO: verify this randomly grabs a random team
            bteam = self.teams.all.order_by("?").first()
            bmatch = Match(hometeam=None, bye_1=True, awayteam=bteam, winner=bteam, completed=True,
                           type='singletournament', maps=self.map_pool, game=self.game, platform=self.platform)
            bmatch.save()
            round1.matches.add(bmatch)
            myteams.remove(bteam)
            if len(myteams) % 2 != 0:
                print("ITS BROKEN YOU SUCK")
                return
            while len(myteams) != 0:
                temp1 = myteams.all().order_by("?").first()
                myteams.remove(temp1)
                myteams.save()
                temp2 = myteams.all().order_by("?").first()
                tempmatch = Match(awayteam=temp1, hometeam=temp2, maps=self.map_pool, game=self.game, platform=self.platform)
                tempmatch.save()
                myteams.remove(temp2)
                myteams.save()
                round1.matches.add(tempmatch)
                round1.save()

        round1.save()
Пример #22
0
def create_match_from_json(match_json,
                           competition_id,
                           stage_name,
                           set_live=False):
    global total_requests
    try:  # First try to get or create teh country
        print("Looking for competition with ID %s .." % competition_id)
        competition = Competition.objects.get(external_id=competition_id)
    except Exception as e:
        print("Error Looking for competition with ID %s .." % competition_id)
        exit(1)
    try:
        match_ext_id = match_json['id']
        print("Processing match with ID %s" % match_ext_id)
        match = Match.objects.get(external_id=match_ext_id)
    except Match.DoesNotExist:
        # Get or create teams
        try:
            team1_ext_id = match_json['localteam_id']
            print("Looking for team1 ext ID %s.." % team1_ext_id)
            team1 = Team.objects.get(competition=competition,
                                     external_id=team1_ext_id)
        except Team.DoesNotExist:
            print("Team with id %s not found" % team1_ext_id)
            return None
        else:
            print("Team 1 found: %s" % team1)

        try:
            team2_ext_id = match_json['visitorteam_id']
            print("Looking for team1 ext ID %s.." % team2_ext_id)
            team2 = Team.objects.get(competition=competition,
                                     external_id=team2_ext_id)
        except Team.DoesNotExist:
            print("Team with id %s not found" % team2_ext_id)
            return None
        else:
            print("Team 2 found: %s" % team2)

        # Continue creating match
        print("Creating new match from json..")
        match = Match()
        match.external_id = match_ext_id
        match.stage = CompetitionStage.objects.get(competition=competition,
                                                   name=stage_name)
        try:
            group_name = match_json['group']['data']['name']
        except Exception:
            try:
                group_name = match_json['stage']['data']['name']
            except Exception:
                group_name = ""
        match.stage_detail = group_name
        from datetime import datetime
        datetime_str = match_json['time']['starting_at']['date_time']
        datetime_object = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        match.date = datetime_object
        match.stadium = match_json['venue']['data']['name']
        match.team1 = team1
        match.team1_score = match_json['scores']['localteam_score']
        match.team2 = team2
        match.team2_score = match_json['scores']['visitorteam_score']
        match.is_live = set_live
        match.save()
        print("Match saved: %s" % match)
    else:
        print("Match %s already exist (skiped).." % match)
    return match
Пример #23
0
 def test_default_score_values(self):
     match = Match()
     self.assertEqual(match.home_score, None)
     self.assertEqual(match.away_score, None)
Пример #24
0
 def test_cant_be_without_fields(self):
     match = Match()
     with self.assertRaises(ValidationError):
         match.full_clean()
def create_match_from_json(team1, team2, match_json):
    global total_requests

    try:
        match_ext_id = match_json['id']
        print("Processing match with ID %s" % match_ext_id)
        match = Match.objects.get(external_id=match_ext_id)
    except Match.DoesNotExist:
        # Continue creating match
        print("Creating new match from json..")
        localteam_id = match_json['localteam_id']
        visitorteam_id = match_json['visitorteam_id']
        if int(team1.external_id) == localteam_id and int(
                team2.external_id) == visitorteam_id:
            local_team = team1
            visitor_team = team2
        else:
            local_team = team2
            visitor_team = team1

        match = Match()
        match.external_id = match_ext_id
        match.stage = None
        match.status = Match.FINISHED
        match.stage_detail = match_json['stage']['data']['name'].lower()
        from datetime import datetime
        datetime_str = match_json['time']['starting_at']['date_time']
        datetime_object = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        match.date = datetime_object
        match.stadium = match_json['venue']['data']['name']
        match.team1 = local_team
        match.team1_score = match_json['scores']['localteam_score']
        match.team2 = visitor_team
        match.team2_score = match_json['scores']['visitorteam_score']
        match.is_live = False
        match.is_history = True  # Historical match <<<
        match.save()
        print("Match saved: %s" % match)
    else:
        print("Match %s already exist (skiped).." % match)
    return match
Пример #26
0
    def post(self, request):
        serializer = ImageSerializer(data=request.data)
        if serializer.is_valid():
            stand = Stand.objects.get(id=serializer.data['stand'])
            frame = from_base64(serializer.data['image'])
            rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            h, w, ch = rgbImage.shape
            face_recognizer = FaceRecognizer.get_instance()
            face_list = face_recognizer.faces(frame)

            for i in range(0, face_list.shape[2]):
                confidence = face_list[0, 0, i, 2]
                if confidence > 0.5:
                    box = face_list[0, 0, i, 3:7] * np.array([w, h, w, h])
                    (startX, startY, endX, endY) = box.astype("int")

                    face = frame[startY:endY, startX:endX]
                    (fH, fW) = face.shape[:2]

                    if fW < 20 or fH < 20:
                        continue

                    cv2.rectangle(frame, (startX, startY), (endX, endY),
                                  (0, 255, 0), 2)
                    cv2.rectangle(frame, (startX, startY), (endX, startY - 66),
                                  (0, 255, 0), cv2.FILLED)
                    y = startY - 10 if startY - 10 > 10 else startY + 10

                    emotion_type = None
                    if stand.emotion:
                        emotion = EmotionRecognizer.get_instance()
                        emotion_id, emotion_percent = emotion.emotion(
                            face=face)
                        emotion_type = EmotionTypes.objects.get(
                            emotion_number=emotion_id)
                        cv2.putText(
                            frame,
                            emotion_type.name + " (" + emotion_percent + ")",
                            (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                            (0, 0, 0), 2)
                        print(emotion_type.name + " (" + emotion_percent + ")")

                    if stand.person:
                        match = Match()
                        match.standID = stand

                        person_recognizer = PersonRecognizer.get_instance()
                        person_text, text = person_recognizer.person(face=face)

                        name = text.split()

                        if len(name) == 2:
                            person = Person.objects.get(name=name[0],
                                                        surname=name[1])
                        else:
                            if len(name) == 1:
                                try:
                                    person = Person.objects.get(name=name[0],
                                                                surname=None)
                                except Exception:
                                    person = None
                        if person:
                            match.personId = person
                            print(person_text)
                            cv2.putText(frame, person_text, (startX, y - 16),
                                        cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                        (0, 0, 0), 2)

                            if stand.emotion:
                                match.emotionId = emotion_type

                            # match.save()
                            # os.chdir(r'C:\Users\gavri\Desktop\фото')
                            # cv2.imwrite("image.jpg", frame)
                    info_point = InfoPoint()
                    info_point.standId = stand

                    if stand.emotion:
                        info_point.emotionTypeID = emotion_type

                    text = ''
                    if stand.age:
                        age_recognizer = AgeRecognizer.get_instance()
                        age = age_recognizer.age(face=face)
                        info_point.age = age
                        text = str(info_point.age) + ', '
                        print(info_point.age)

                    if stand.sex:
                        sex_recognizer = GenderRecognizer.get_instance()
                        sex = sex_recognizer.gender(face=face)
                        info_point.sex = sex
                        text += str(info_point.SEXES[sex - 1][1])
                        print(info_point.SEXES[sex - 1][1])

                    cv2.putText(frame, text, (startX, y - 32),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
                    # info_point.save()
                    # os.chdir(r'C:\Users\gavri\Desktop\фото')
                    # cv2.imwrite("image.jpg", frame)

            return Response(to_base64(frame), status=status.HTTP_200_OK)
        return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #27
0
    def _parse_fixture(self, simulate, fixture_season, fixture_date, club_team, fields):
        """ Creates/updated a match model instance based on the relevant fields from the CSV file."""
        # Slight hack to decide whether the fixture is specified or not
        if fields[OFFSET['fixture_type']] == "":
            print "No match for {} on {}".format(club_team['name'], fixture_date)
            return

        team_name = club_team['name']
        our_team = club_team['team']
        fixture_type = fields[OFFSET['fixture_type']]
        opp_team_name = fields[OFFSET['opposition']]
        venue_name = fields[OFFSET['venue']]
        fixture_time_str = fields[OFFSET['time']]
        home_away = fields[OFFSET['home_away']]

        try:
            opp = Team.objects.get(name=opp_team_name)
        except Team.DoesNotExist:
            print "ERROR: Could not find opposition team with name '{}'".format(opp_team_name)
            return

        # Create or retrieve Match model (based on opposition team, our team and date)
        if not simulate:
            match, created = Match.objects.get_or_create(season=fixture_season, opp_team=opp, our_team=our_team, date=fixture_date)
        else:
            created = not Match.objects.filter(season=fixture_season, opp_team=opp, our_team=our_team, date=fixture_date).exists()
            match = Match(season=fixture_season, opp_team=opp, our_team=our_team, date=fixture_date)

        # Match home/away designation
        try:
            match.home_away = HOME_AWAY[home_away.lower()]
        except:
            print "ERROR: Invalid Home/Away designation '{}' for {} on {}".format(home_away, team_name, fixture_date)
            return

        # Match fixture type (League/Cup/Friendly)
        try:
            match.fixture_type = MATCH_TYPE[fixture_type.lower()]
        except:
            print "ERROR: Invalid fixture type designation '{}' for {} on {}".format(fixture_type, team_name, fixture_date)
            return

        # Match time (can be null)
        if fixture_time_str:
            try:
                match.time = datetime.strptime(fixture_time_str, "%H:%M").time()
            except:
                print "ERROR: Could not parse fixture time '{}' for {} on {}".format(fixture_time_str, team_name, fixture_date)
                return
        else:
            match.time = None


        # Match Venue (can be null)
        if venue_name.lower() == 'away' or (home_away.lower() == 'a' and venue_name.lower() == ''):
            match.venue = None
        else:
            try:
                name_q = Q(name=venue_name) | Q(short_name=venue_name)
                match.venue = Venue.objects.get(name_q)
            except Venue.DoesNotExist:
                print "ERROR: Could not find venue '{}' for {} on {}".format(venue_name, team_name, fixture_date)
                return

        if not simulate:
            match.save()

        print "{} {}".format("Created" if created else "Updated", match)
Пример #28
0
    def generate_bracket(self):
        # seed teams and make matches
        game = self.game
        platform = self.platform
        teamformat = self.teamformat
        bestof = self.bestof
        size = self.size
        numteams = self.teams.count()
        bye = size - numteams
        teams = list(self.teams.all())

        for team in teams:
            team.get_total_xp()

        count = 1
        seeds = []
        while count <= size:
            seeds.append(count)
            count += 1

        team_seeds = []
        max_matches = size / 2
        if not self.xp_seed:
            random.shuffle(teams)
        else:
            teams = self.teams.order_by('-totalxp')

        for i in teams:
            team_seeds.append(i)

        m = dict()
        if bye == 2 or bye == 1:
            offset = 0
        else:
            offset = -2
        skipotherbye = False

        if bye >= 3:
            if bye % 2 != 0:
                hometeam = team_seeds[0]
                hometeam.seeds = seeds[0]
                hometeam.save()
                round1 = SingleTournamentRound.objects.get(tournament=self,
                                                           roundnum=1)
                # bye_1 specifies that the match has only 1 bye team in it, and that one team is being automatically
                # advanced to the next round
                m[1] = Match(
                    game=game,
                    matchnum=1,
                    platform=platform,
                    hometeam=team_seeds[0],
                    teamformat=teamformat,
                    bestof=bestof,
                    reported=True,
                    completed=True,
                    winner=team_seeds[0],
                    bye_1=True,
                    info=round1.info,
                    # disable user reports based on the tournament field value
                    disable_userreport=True,
                    sport=self.sport)
                m[1].save()

                round1.matches.add(m[1])
                round1.save()
                del team_seeds[0]
                del seeds[0]

                bye -= 1

            if bye % 2 == 0:
                byematches = bye / 2

                for i in range(1, int(byematches) + 1):
                    round1 = SingleTournamentRound.objects.get(tournament=self,
                                                               roundnum=1)
                    # bye_2 specifies that both teams are bye teams, therefor a team will receive a bye in the first
                    # and second round
                    m[i] = Match(game=game,
                                 matchnum=i,
                                 platform=platform,
                                 teamformat=teamformat,
                                 bestof=bestof,
                                 reported=True,
                                 sport=self.sport,
                                 completed=True,
                                 bye_2=True,
                                 info=round1.info,
                                 disable_userreport=True)
                    m[i].save()

                    round1.matches.add(m[i])
                    round1.save()
                skipotherbye = True
        elif bye == 2 and not skipotherbye:
            round1 = SingleTournamentRound.objects.get(tournament=self,
                                                       roundnum=1)

            m[1] = Match(game=game,
                         matchnum=1,
                         platform=platform,
                         teamformat=teamformat,
                         bestof=bestof,
                         reported=True,
                         sport=self.sport,
                         completed=True,
                         bye_2=True,
                         info=round1.info,
                         disable_userreport=True)
            m[1].save()

            round1.matches.add(m[1])
            round1.save()
        if bye != 0:
            for x in range(bye + 1, int(max_matches) + bye + offset):

                if len(team_seeds) == 0:
                    break

                if len(team_seeds) == 1:
                    hometeam = team_seeds[0]
                    hometeam.seeds = seeds[0]
                    hometeam.save()
                    round1 = SingleTournamentRound.objects.get(tournament=self,
                                                               roundnum=1)

                    m[x] = Match(game=game,
                                 matchnum=x,
                                 platform=platform,
                                 hometeam=team_seeds[0],
                                 teamformat=teamformat,
                                 bestof=bestof,
                                 reported=True,
                                 sport=self.sport,
                                 completed=True,
                                 winner=team_seeds[0],
                                 bye_1=True,
                                 info=round1.info,
                                 disable_userreport=True)
                    m[x].save()

                    round1.matches.add(m[x])
                    round1.save()
                    break

                hometeam = team_seeds[0]
                hometeam.seed = seeds[0]
                hometeam.save()
                awayteam = team_seeds[-1]
                awayteam.seed = seeds[-1]
                awayteam.save()
                round1 = SingleTournamentRound.objects.get(tournament=self,
                                                           roundnum=1)

                m[x] = Match(
                    game=game,
                    platform=platform,
                    hometeam=team_seeds[0],
                    awayteam=team_seeds[-1],
                    teamformat=teamformat,
                    bestof=bestof,
                    info=round1.info,
                    sport=self.sport,
                    # this is an actual match, so disable user reports based on the field setting
                    disable_userreport=self.disable_userreport)
                m[x].save()
                round1.matches.add(m[x])
                round1.save()

                del team_seeds[0]
                del team_seeds[-1]
                del seeds[0]
                del seeds[-1]
        else:
            for x in range(1, int(max_matches) + 1):

                if len(team_seeds) == 1:
                    hometeam = team_seeds[0]
                    hometeam.seeds = seeds[0]
                    hometeam.save()
                    round1 = SingleTournamentRound.objects.get(tournament=self,
                                                               roundnum=1)

                    m[x] = Match(game=game,
                                 matchnum=x,
                                 platform=platform,
                                 hometeam=team_seeds[0],
                                 teamformat=teamformat,
                                 bestof=bestof,
                                 reported=True,
                                 sport=self.sport,
                                 completed=True,
                                 winner=team_seeds[0],
                                 bye_1=True,
                                 info=round1.info,
                                 disable_userreport=True)
                    m[x].save()

                    round1.matches.add(m[x])
                    round1.save()
                    break

                hometeam = team_seeds[0]
                hometeam.seed = seeds[0]
                hometeam.save()
                awayteam = team_seeds[-1]
                awayteam.seed = seeds[-1]
                awayteam.save()
                round1 = SingleTournamentRound.objects.get(tournament=self,
                                                           roundnum=1)

                m[x] = Match(game=game,
                             platform=platform,
                             hometeam=team_seeds[0],
                             awayteam=team_seeds[-1],
                             teamformat=teamformat,
                             bestof=bestof,
                             info=round1.info,
                             sport=self.sport,
                             disable_userreport=self.disable_userreport)
                m[x].save()
                round1.matches.add(m[x])
                round1.save()

                del team_seeds[0]
                del team_seeds[-1]
                del seeds[0]
                del seeds[-1]
Пример #29
0
class TestMatchesViewset(TestCase):
    def setUp(self):
        self.character = Character(name='Test', role=Character.DAMAGE)
        self.character.save()

        self.owner = User.objects.create_user('owner')
        self.notOwner = User.objects.create_user('notowner')

        self.match = Match(user=self.owner, mmr_after=1000)
        self.match.save()
        self.match.characters.set([self.character])

        self.client = APIClient()
    
    API_MATCHES_LIST_URL = '/api/matches/'
    def testListsOnlyMatchesOfLoggedUser(self):
        """
        GET request to API_MATCHES_LIST_URL should return only matches of logged user
        """
        self.client.force_authenticate(user=self.owner)
        response = self.client.get(self.API_MATCHES_LIST_URL)
        self.assertEqual(
            status.HTTP_200_OK,
            response.status_code,
            'Request response code should be 200 (OK)'
        )
        self.assertEqual(
            1,
            len(response.data),
            'Response data should contain 1 object'
        )
        self.assertEqual(
            self.match.pk,
            response.data[0]['id'],
            'Object in response data should be match that belongs to user'
        )
        self.client.logout()

        self.client.force_authenticate(user=self.notOwner)
        response = self.client.get(self.API_MATCHES_LIST_URL)
        self.assertEqual(
            status.HTTP_200_OK,
            response.status_code,
            'Request response code should be 200 (OK)'
        )
        self.assertEqual(
            0,
            len(response.data),
            'Response data should contain 0 objects'
        )
        self.client.logout()

    API_MEW_MATCH_URL = API_MATCHES_LIST_URL
    def testCreatedMatchBelongsToCurrenltyLoggedInUser(self):
        """
        POST request to API_NEW_MATCH_URL should automatically assign User
        """
        data = {
            'characters': [self.character.pk],
            'mmr_after': 5000
        }
        self.client.force_authenticate(user=self.owner)
        response = self.client.post(self.API_MEW_MATCH_URL, data=data)
        self.assertEqual(
            status.HTTP_201_CREATED,
            response.status_code,
            'Request response code should be 201 (Created)'
        )
        new_match = Match.objects.get(id=response.data['id'])
        self.assertEqual(
            new_match.user,
            self.owner,
            'User field of recently created match should be assigned to currently logged user'
        )
        self.client.logout()