def quick(self, request): res = Result() context = self._processRequest(request) serobj = context['request'].POST.get('q', False) if serobj: obj = json.loads(serobj) ladder = Ladder.objects.get(pk=obj['ladder']) red = Team.objects.get(pk=obj['red']) blu = Team.objects.get(pk=obj['blu']) games = [] for n in xrange(obj['red_wins']): g = Game(ladder=ladder, red=red, blu=blu) g.save() g.update(red) games.append(g) for n in xrange(obj['blu_wins']): g = Game(ladder=ladder, red=red, blu=blu) g.save() g.update(blu) games.append(g) res.isSuccess = True res.append([g.json() for g in games]) else: res.isError = True res.message = "No query provided" return JsonResponse(res)
def create(self, request): res = Result() #context = self._processRequest(request) ladder = Ladder.objects.get(pk=request.POST.get('lid', None)) red = Team.objects.get(pk=request.POST.get('red', None)) blu = Team.objects.get(pk=request.POST.get('blu', None)) if len(set(red.members.all()).intersection(blu.members.all())) > 0: res.isError = True res.message = CH_SAME_TEAM return JsonResponse(res) game = Game() game.ladder = ladder game.red = red game.blu = blu game.save() res.isSuccess = True res.message = CH_SUCCESS #mail('You have been challenged!', 'ladder/email/game.html', {'object': game}, [user.email for user in game.blu.members.all()]) return JsonResponse(res)
def ratingGraph(self, request, obj_id): res = Result() team = Team.objects.get(pk=obj_id) ladderID = request.GET.get('ladder', None) if ladderID: try: ladder = Ladder.objects.get(pk=ladderID) except ObjectDoesNotExist: raise Http404 else: try: ladder = RatingHistory.objects.filter(team=team).latest().ladder except ObjectDoesNotExist: raise Http404 ratings = RatingHistory.objects.filter(ladder=ladder, team=team).order_by('id') data = { 'title': ladder.name, 'rows': [[int(rating.rating),] for rating in ratings], 'rowNames': [], 'colNames': [team.name,], } res.isSuccess = True res.append(data) return JsonResponse(data)
def get(self, request, obj_id, requestData={}): context = requestData if request.GET.get('json', False): res = Result() res.isSuccess = True res.append(context['object'].json()) return JsonResponse(res) redGames = Game.objects.filter(red__exact=context['id'], status=Game.Closed) bluGames = Game.objects.filter(blu__exact=context['id'], status=Game.Closed) games = redGames | bluGames game_hist = [] for n in games: obj = { 'opponent': n.blu if context['object'] == n.red else n.red, 'ladder': n.ladder, 'status': n.status, 'win': n.result == context['object'], 'date': n.created, 'delta': n.red_change if context['object'] == n.red else n.blu_change, } game_hist.append(obj) context['games'] = game_hist context['isMember'] = True if (context['object'].members.filter(username=context['request'].user.username).count()) > 0 else False return render(request, 'ladder/team.html', context)
def get(self, request, obj_id): result = Result() obj = Match.objects.get(pk=obj_id) result.isSuccess = True result.setValue(obj.json()) return JsonResponse(result)
def ticker(self, request): res = Result() res.isSuccess = True for g in Game.objects.filter(status=Game.Closed)[:5]: res.append(g.json()) return JsonResponse(res)
def view(self, request, obj_id): #self._processRequest(request, obj_id) res = Result() res.isSuccess = True res.append(userToJson(context['object'])) return JsonResponse(res)
def validateName(self, request): #self._processRequest(request) t = Team.objects.filter(name=request.GET.get('name', None)) res = Result() res.isSuccess = True res.append(not bool(len(t))) return JsonResponse(res)
def init(self, request, obj_id): t = Tournament.objects.get(pk=obj_id) t.init() result = Result() result.isSuccess = True result.message = "All matches have been generated" return JsonResponse(result)
def index(self, request): self._processRequest(request) tournaments = [t.json('match') for t in Tournament.objects.filter(state=Tournament.Open, public=True)] self._getContext(tournaments=tournaments) if self.GET.get('json', False): result = Result() result.isSuccess = True result.values = tournaments result.value = result.values[0] if len(result.values) > 0 else None return JsonResponse(result) return self.render()
def manual(self, request, obj_id): """ Handles manual game entries """ res = Result() message = '' error = False context = self._processRequest(request, obj_id) red = Team.objects.get(pk=request.POST.get('red', None)) blu = Team.objects.get(name=request.POST.get('blu', None)) games = request.POST.get('games', '').split(',') if request.user in red.members.all() and request.user in blu.members.all(): error = True message = IN_BOTH_TEAMS try: red.laddermembership_set.get(ladder=context['object']) except ObjectDoesNotExist: message = RED_NOT_MEMBER error = True try: blu.laddermembership_set.get(ladder=context['object']) except ObjectDoesNotExist: message = BLU_NOT_MEMBER error = True if error: res.isError = True res.message = message return JsonResponse(res) forMail = [] for game in games: winner = 'red' if game == '0' else 'blu' game = Game( ladder = context['object'], red = red, blu = blu, status = Game.Closed ) game.save() game.update(winner) forMail.append(game) time.sleep(1) self.mail_manual(request.user, forMail) res.isSuccess = True res.message = message return JsonResponse(res)
def post(self, request, *args, **kwargs): result = Result() if kwargs.get('obj_id', None): self._processRequest(request, kwargs['obj_id']) if self.POST.get('start'): self.object.state = Tournament.Started self.object.save() result.isSuccess = True return JsonResponse(result) else: self.object = Tournament() for k,v in request.POST.iteritems(): if hasattr(self.object, k): try: v = int(v) except ValueError: pass if v.lower() == 'true': v = True elif v.lower() == 'false': v = False setattr(self.object, k, v) else: result.isError = True result.message = "Invalid property: %s" % k break if not result.isError: self.object.save() result.isSuccess = True return JsonResponse(result)
def put(self, request, obj_id, requestData={}): context = requestData res = Result() status = context['PUT'].get('status', None) if status: context['object'].status = int(status) context['object'].save() res.isSuccess = True res.message = "Status update to %i" % context['object'].status else: res.isError = True res.message = "Status was missing or invalid" return JsonResponse(res)
def query(self, request): q = request.POST.get('search', '') results = [] res = Result() if q: users = User.objects.filter(Q(username__icontains=q) | Q(first_name__icontains=q) | Q(last_name__icontains=q)) for n in users: results.append([n.id, n.username]) res.isSuccess = True res.append(results) else: res.isError = True res.message = 'No search query provided' return JsonResponse(res)
def history(self, request, obj_id): team = Team.objects.get(pk=obj_id) limit = request.GET.get('limit', None) redGames = Game.objects.filter(red__exact=team.id, status=Game.Closed) bluGames = Game.objects.filter(blu__exact=team.id, status=Game.Closed) games = redGames | bluGames if limit: games = games[:int(limit)] res = Result() res.isSuccess = True for game in games: res.append(game.json()) return JsonResponse(res)
def index(self, request): self._processRequest(request) result = Result() qs = Q() for n in self.user.teams.all(): qs |= Q(red=n) qs |= Q(blu=n) matches = Match.objects.filter(qs, state=Match.Open) obj = [m.json() for m in matches] result.isSuccess = True result.setValue(obj) return JsonResponse(result)
def getTeams(self, request): userID = request.GET.get('id', None) teamSize = request.GET.get('team_size', None) data = False if userID: obj = User.objects.get(pk=userID) teams = obj.teams.all() if teamSize: teams = teams.filter(laddermembership__ladder__team_size=int(teamSize)) data = [team.json() for team in teams] res = Result() res.isSuccess = True res.append(data) return JsonResponse(res)
def history(self, request, obj_id, returnType=None): context = self._processRequest(request, obj_id) res = Result() limit = request.GET.get('limit', None) teams = context['object'].teams.values_list('id', flat=True).order_by('id') games = Game.objects.filter(Q(red__in=teams) | Q(blu__in=teams)) if limit: games = games[:int(limit)] if returnType == 'object': return games elif returnType == 'json': return [game.json() for game in games] else: res.isSuccess = True res.append([game.json() for game in games]) return JsonResponse(res)
def join(self, request, obj_id, context): """ Joins a team to a ladder """ res = Result() teamId = context['request'].POST.get('team', None) if teamId: try: team = Team.objects.get(pk=teamId) except ObjectDoesNotExist: res.isError = True res.message = "Team not found" return JsonResponse(res) if context['object'].laddermembership_set.filter(team=team).count() > 0: res.isError = True res.message = ALREADY_MEMBER return JsonResponse(res) if len(team) != context['object'].team_size: res.isError = True res.message = L_INCORRECT_SIZE % context['object'].team_size return JsonResponse(res) # Get a new rating object rating = RatingHistory(team=team,ladder=context['object']) rating.save() lm = LadderMembership(team=team, ladder=context['object'], rating=rating) lm.save() res.isSuccess = True res.append(team.json()) #self.mail_join(team) return JsonResponse(res) else: res.isError = True res.message = "No team provided" return JsonResponse(res)
def put(self, request, obj_id): result = Result() tourn = Tournament.objects.get(pk=obj_id) if tourn.state != Tournament.Open: result.isError = True result.message = "This tournament is not open" return JsonResponse(result) teamID = self.PUT.get('team', None) if teamID: team = Team.objects.get(pk=teamID) if team.members.all().count() != tourn.team_size: result.isError = True result.message = "%s does not have the correct number of players (%i) to join this tournament" % (team.name, tourn.team_size) return JsonResponse(result) hasJoined = tourn.matches.filter(Q(red=team) | Q(blu=team), round=1) if len(hasJoined): result.message = '%s has already joined this tournament' % team.name result.isError = True return JsonResponse(result) matches = tourn.matches.filter(red__isnull=True, round=1) if not matches: matches = tourn.matches.filter(blu__isnull=True, round=1) match = random.choice(matches) if match.red: match.blu = team else: match.red = team tourn.teams.add(team) match.save() result.isSuccess = True else: result.isError = True result.message = "No team provided" return JsonResponse(result)
def challenge(self, request, obj_id): """ Handles manual challenges """ res = Result() context = self._processRequest(request, obj_id) red = Team.objects.get(pk=request.POST.get('red', None)) blu = Team.objects.get(pk=request.POST.get('blu', None)) if request.user in blu.members.all(): res.isError = True res.message = CH_SAME_TEAM return JsonResponse(res) game = Game(ladder=context['object'], red=red, blu=blu, status=Game.Open) game.save() res.isSuccess = True res.message = CH_SUCCESS #self.mail_challenge(challenge) return JsonResponse(res)
def post(self, request, obj_id): result = Result() matchResult = self.POST.get('result', False) if matchResult: obj = Match.objects.get(pk=obj_id) teams = request.user.teams.all() if obj.red not in teams and obj.blu not in teams: result.isError = True result.message = "You are not a member of a team in this match" else: winner = Team.objects.get(pk=matchResult) matchTeams = [obj.red, obj.blu] if winner not in matchTeams: result.isError = True result.message = "Team ID provided is not in this match" return JsonResponse(result) if obj.state != Match.Open: result.isError = True result.message = "Match is not open" return JsonResponse(result) newMatch = obj.promote(winner) if newMatch.state == Match.Open: # mail new teams pass result.isSuccess = True result.message = "Match result recorded: %s %s %s" % (obj.red.name, '>' if winner == obj.red else '<', obj.blu.name) else: result.isError = True result.message = "No winning team ID provided" return JsonResponse(result)
def update(self, request, obj_id, context): """ Does the maths for the result of the game and closes it out """ updatePending() res = Result() request.POST if context['object'].status != 0: res.isError = True res.message = "This game is not open" return JsonResponse(res) if context['request'].user in context['object'].red.members.all() or context['request'].user in context['object'].blu.members.all(): result = request.POST.get('result', None) if not result: res.isError = True res.message = "Incorrect result type, int required" return JsonResponse(res) context['object'].update(Team.objects.get(pk=result)) # Send the emails of the results red = [user.email for user in context['object'].red.members.all()] blu = [user.email for user in context['object'].blu.members.all()] #mail('Game has ended', 'ladder/email/game.html', {'game': context['object'], 'user': context['request'].user}, red + blu) res.isSuccess = True res.message = "Game is now closed" res.append(context['object'].json()) else: res.isError = True res.message = 'You are not a member of either team for this game.' return JsonResponse(res)
def language(self, request): res = Result() if request.method != 'POST': res.isError = True res.message = "Invalid method, use POST" return JsonResponse(res) query = request.POST.get('q', None) if query: try: obj = parse(query) except: res.isError = True res.message = "Could not understand your request" return JsonResponse(res, 500) try: ladder = Ladder.objects.get(name=obj['ladder']) except ObjectDoesNotExist: res.isError = True res.message = "The ladder requested was not found" return JsonResponse(res, 500) ## Red if obj['red'] in ['i', 'me']: try: red = request.user.teams.filter(ladder=ladder)[0] if ladder.teams.filter(name=obj['blu']).count() == 0: res.isError = True res.message = "Your opponent (%s) does not have any teams in the %s ladder" % (obj['blu'], ladder.name) return JsonResponse(res, 500) except: res.isError = True res.message = "You do not have any teams in the %s ladder" % ladder.name return JsonResponse(res, 500) else: try: red = Team.objects.get(name=obj['red']) except ObjectDoesNotExist: res.isError = True res.message = "The team '%s' was not found" % obj['red'] return JsonResponse(res, 500) ## Blue if obj['blu'] in ['i', 'me']: try: blu = request.user.teams.filter(ladder=ladder)[0] if ladder.teams.filter(name=obj['red']).count() == 0: res.isError = True res.message = "Your opponent (%s) does not have any teams in the %s ladder" % (obj['red'], ladder.name) return JsonResponse(res, 500) except: res.isError = True res.message = "You do not have any teams in the %s ladder" % ladder.name return JsonResponse(res, 500) else: try: blu = Team.objects.get(name=obj['blu']) except ObjectDoesNotExist: res.isError = True res.message = "The team '%s' was not found" % obj['blu'] return JsonResponse(res, 500) winner = red if obj['winner'] == 'red' else blu g = Game(red=red, blu=blu, ladder=ladder) g.save() g.update(winner) res.isSuccess = True res.message = g.json() else: res.isError = True res.message = "No query provided" return JsonResponse(res)