def form_valid(self, form): sender = "*****@*****.**" # sender = "*****@*****.**" if form.is_valid(): # send email using the self.cleand_data dictionary subject = form.cleaned_data['subject'] body = form.cleaned_data['body'] recipient_title = form.cleaned_data['recipient'] # based on inputs from the recipients field, retrieve the list of players # to send emails to, options are: # all players, humans, or zombies if (recipient_title == MailerForm.ALLPLAYERS): recipients = [p.user.email for p in Player.current_players()] elif (recipient_title == MailerForm.HUMANS): recipients = [ p.user.email for p in Player.current_players() if p.team == "H" ] elif (recipient_title == MailerForm.ZOMBIES): recipients = [ p.user.email for p in Player.current_players() if p.team == "Z" ] # send mail based on the given inputs send_mail(subject, body, sender, recipients) return super(Mailer, self).form_valid(form)
def make_meals(self, num_meals): humans = list(Player.current_players().filter(team='H')) zombies = list(Player.current_players().filter(team='Z')) g = Game.imminent_game() days = (g.end_date - g.start_date).days day = g.start_date while day < g.end_date: meals_per_hour = [0 for i in xrange(24)] for i in xrange(int(num_meals / days)): meals_per_hour[int(random.gauss(13, 4)) % 24] += 1 for hour in xrange(24): for meal in xrange(meals_per_hour[hour]): z = int(random.random() * len(zombies)) h = int(random.random() * len(humans)) Meal( eater=zombies[z], eaten=humans[h], time=datetime.combine(day, time(hour=hour)), location=random.choice(Building.objects.all()), ).save() # Instead of retrieving the entire zombie and human lists # again, why don't we just add the human to the zombie # horde ourselves? zombies.append(humans.pop(h)) day += timedelta(days=1)
def form_valid(self, form): kindOptions = {"Humans": "H", "ZOMBIES": "Z"} sender = "*****@*****.**" # sender = "*****@*****.**" if form.is_valid(): # send email using the self.cleand_data dictionary subject = form.cleaned_data['subject'] body = form.cleaned_data['body'] recipient_title = form.cleaned_data['recipient'] schoolSelection = form.cleaned_data['school'] kind_recipients = [] kind_label = "[" + recipient_title + "]" # Using a dictionary to have more robust way to select players if (recipient_title in kindOptions): kind_recipients = [ p.user.email for p in Player.current_players() if p.team == kindOptions[recipient_title] ] else: # Default recipients list is all players kind_recipients = [p.user.email for p in Player.current_players()] subject = kind_label + subject school_recipients = [] for schools in schoolSelection: school_label = "[" + schools + "]" subject = school_label + subject school_recipients.append([ p.user.email for p in Player.current_players() if p.school.name == schools ]) # flatten the list of lists school_recipients = [ item for sublist in school_recipients for item in sublist ] # combine two lists to get to right list of recipients recipients = [] if (len(school_recipients) == 0): recipients = kind_recipients else: recipients = list( set(kind_recipients).intersection(set(school_recipients))) # TODO: Authentication error for sender for [email protected] mailBag = EmailMessage(subject, body, sender, [], recipients) mailBag.send(fail_silently=False) return super(Mailer, self).form_valid(form)
def save(self, commit=False): def grab(s): return self.cleaned_data[s] game = Game.nearest_game() player = Player.user_to_player(self.user, game) self.thread = Thread( game=game, team=grab('team'), title=grab('title'), slug=slugify(grab('title')), ) self.thread.save() post = Post( author=player, thread=self.thread, body=grab('post_body'), created=settings.NOW(), ) if commit: post.save() return self.thread
def thread_detail_view(request, pk, slug): thread = get_object_or_404(Thread, pk=pk) player = Player.user_to_player(request.user, thread.game) if not thread.visible_to_player(player): raise PermissionDenied('You cannot see this thread!') if request.method == 'POST': form = PostCreateForm(request.POST, player=player, thread=thread) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect( reverse( 'thread_detail', kwargs={ 'pk': int(pk), 'slug': slug }, )) else: form = PostCreateForm(player=player, thread=thread) return render( request, 'forum/thread-detail.html', { 'form': form, 'thread': thread, 'player': player, 'posts': Post.objects.filter(thread=thread).order_by('created') }, )
def thread_detail_view(request, pk, slug): thread = get_object_or_404(Thread, pk=pk) player = Player.user_to_player(request.user, thread.game) if not thread.visible_to_player(player): raise PermissionDenied('You cannot see this thread!') if request.method == 'POST': form = PostCreateForm(request.POST, player=player, thread=thread) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect( reverse( 'thread_detail', kwargs = {'pk': int(pk), 'slug': slug}, ) ) else: form = PostCreateForm(player=player, thread=thread) return render( request, 'forum/thread-detail.html', { 'form': form, 'thread': thread, 'player': player, 'posts': Post.objects.filter(thread=thread).order_by('created') }, )
def set_player(self, request): if self.player: return try: self.player = Player.user_to_player(request.user, self.get_game()) except Player.DoesNotExist: raise PermissionDenied("You are not registered for this game!")
def clean_feed(self): """Ensure that the same feed code is not used twice in the same game.""" feedcode = self.cleaned_data['feed'] if Player.current_players().filter(feed=feedcode).exists(): raise ValidationError(self.error_messages['duplicate_feed']) return feedcode
def clean_email(self): """Ensure that a user does not register twice for the same game.""" email = self.cleaned_data['email'] if Player.current_players().filter(user__username=email).exists(): raise ValidationError(self.error_messages['duplicate_user']) return email
def clean_email(self): """Ensure that a user does not register twice for the same game.""" email = self.cleaned_data['email'] if Player.current_players().filter( Q(user__username=email) | Q(user__email=email)).exists(): raise ValidationError(self.error_messages['duplicate_user']) return email
def json_get_current_player_name(request): """Returns the concatenated first and last names of the logged in player.""" name = Player.logged_in_player(request).user.get_full_name(); json_data = json.dumps(name); return HttpResponse( json_data, content_type="application/json" )
def pick_ozs(self, num_ozs): ozs = Player.current_players().order_by('?')[:num_ozs] for p in ozs: # Retroactively volunteer the mock player p.can_oz = True p.team = 'Z' p.upgrade = 'O' p.save()
def player(self): if self._player: return self._player try: self._player = Player.user_to_player(self.request.user, self.game) except Player.DoesNotExist: raise PermissionDenied("You are not registered for this game!") return self._player
def json_get_current_player_team(request): """Returns H or Z, corresponding to logged in player's team.""" team = Player.logged_in_player(request).team json_data = json.dumps(team) return HttpResponse( json_data, content_type="application/json" )
def check_team(u): try: player = Player.user_to_player(u) except Player.DoesNotExist: raise PermissionDenied("You are not registered for this game!") if player.team != team: team_name = "human" if team == 'H' else "zombie" raise PermissionDenied("You must be a {} to view this page.".format(team_name)) return True
def form_valid(self, form): failure_url = '/api/failure/' sender = "*****@*****.**" # sender = "*****@*****.**" if form.is_valid(): # send email using the self.cleand_data dictionary subject = form.cleaned_data['subject'] body = form.cleaned_data['body'] recipient_title = form.cleaned_data['recipient'] # based on inputs from the recipients field, retrieve the list of players # to send emails to, options are: # all players, humans, or zombies if(recipient_title == MailerForm.ALLPLAYERS): recipients = [p.user.email for p in Player.current_players()] elif(recipient_title == MailerForm.HUMANS): recipients = [p.user.email for p in Player.current_players() if p.team == "H"] elif(recipient_title == MailerForm.ZOMBIES): recipients = [p.user.email for p in Player.current_players() if p.team == "Z"] # option to send emails to players from a specific college # should we add Keck and CGU as well? elif(recipient_title == MailerForm.HMC): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Mudd"] elif(recipient_title == MailerForm.CMC): recipients = [p.user.email for p in Player.current_players() if p.school.name == "CMC"] elif(recipient_title == MailerForm.PITZER): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Pitzer"] elif(recipient_title == MailerForm.POMONA): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Pomona"] elif(recipient_title == MailerForm.SCRIPPS): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Scripps"] # TODO: Authentication error for sender for [email protected] mailBag = EmailMessage(subject, body, sender, [], recipients) try: mailBag.send(fail_silently=False) except Exception as ex: global exception exception = ex return redirect(failure_url) return super(Mailer, self).form_valid(form)
def check_team(u): try: player = Player.user_to_player(u) except Player.DoesNotExist: raise PermissionDenied("You are not registered for this game!") if player.team != team: team_name = "human" if team == 'H' else "zombie" raise PermissionDenied( "You must be a {} to view this page.".format(team_name)) return True
def get_queryset(self): queryset = Player.current_players() if self.kwargs.get('gradyear'): queryset = queryset.filter(grad_year=self.kwargs['gradyear']) if self.kwargs.get('school'): queryset = queryset.filter( school__name__istartswith=self.kwargs['school']) return (queryset.select_related('user', 'school__name').annotate( meal_count=Count('meal_set')).order_by('-meal_count'))
def handle(self, *args, **options): try: self.game = Game.imminent_game() except Game.DoesNotExist: # Create game and players call_command( 'randomplayers', players=options.get('players'), ozs=options.get('ozs'), password=options.get('password'), stdout=self.stdout, stderr=self.stderr, ) self.game = Game.imminent_game() humans = Player.current_players().filter(team='H') zombies = Player.current_players().filter(team='Z') if not len(humans) or not len(zombies): self.stderr.write( '\n'.join(["There are no players in the current game.", "To generate a batch of random players, run", " ./manage.py randomplayers"])) return num_meals = options.get('meals') or len(humans) / 2 self.stdout.write("Creating {} meals".format(num_meals)) if not num_meals: return if len(humans) < num_meals: self.stderr.write( "There are only {} humans in the current game.".format(len(humans)) ) num_meals = len(humans) meals = self.make_meals(num_meals) Meal.objects.bulk_create(meals)
def visible_to_user(self, user): if not user: return False if user.is_staff: return True try: player = Player.user_to_player(user, self.game) except Player.DoesNotExist: return False return self.visible_to_player(player)
def get_queryset(self): queryset = Player.current_players() if self.kwargs.get('gradyear'): queryset = queryset.filter(grad_year=self.kwargs['gradyear']) if self.kwargs.get('school'): queryset = queryset.filter(school__name__istartswith=self.kwargs['school']) return (queryset. select_related('user', 'school__name'). annotate(meal_count=Count('meal_set')). order_by('-meal_count'))
def get_context_data(self, **kwargs): context = super(PlayerListView, self).get_context_data(**kwargs) context['game_season'] = Game.nearest_game().season() context['schools'] = School.objects.all().annotate( num_players=Count('player_set')).order_by('-num_players') context['years'] = map( str, sorted(set([p.grad_year for p in Player.current_players()]))) context['school'] = self.kwargs.get('school', '') context['gradyear'] = self.kwargs.get('gradyear', '') return context
def get_context_data(self, **kwargs): context = super(PlayerListView, self).get_context_data(**kwargs) context['game_season'] = Game.nearest_game().season() context['schools'] = School.objects.all().annotate( num_players=Count('player_set') ).order_by('-num_players') context['years'] = map(str, sorted(set([p.grad_year for p in Player.current_players()]))) context['school'] = self.kwargs.get('school', '') context['gradyear'] = self.kwargs.get('gradyear', '') return context
def filter_forums(self, user, qs): """Players should not be able to see the other team's forums.""" if not user.is_authenticated(): raise PermissionDenied("You are not logged in!") try: vb_team = settings.VERBOSE_TEAMS[Player.user_to_player(user).team] except Player.DoesNotExist: raise PermissionDenied("You are not in this game!") # Display the forums for our team or both teams. both_or_ours = Q(name=vb_team) | Q(name=settings.VERBOSE_TEAMS['B']) return super(ForumPermissionHandler, self).filter_forums(user, qs).filter(both_or_ours)
def raw_serialization(self, context): game = Game.nearest_game() t0, tf = time_endpoints(game) players = Player.current_players().all() meals = Meal.objects.select_related('eaten').all() eaten_zombies = set([m.eaten for m in meals]) ozs = [p for p in players if p.team == 'Z' and p not in eaten_zombies] num_zombies = len(ozs) num_humans = len(players) - num_zombies human_tally = [] zombie_tally = [] meals_vs_hours = meals_per_hour(game, self.get_queryset()) for hour in xrange(len(meals_vs_hours)): t = t0 + timedelta(hours=hour) # Stop the graph at the current time if t > settings.NOW(): break meal_count = meals_vs_hours[hour] num_humans -= meal_count num_zombies += meal_count human_tally.append([json_format_time(t), num_humans]) zombie_tally.append([json_format_time(t), num_zombies]) if not human_tally: human_tally = [[json_format_time(t0), num_humans]] if not zombie_tally: zombie_tally = [[json_format_time(t0), num_zombies]] return [ { 'label': 'humans', 'data': human_tally, 'color': 'rgb(128, 0, 0)' }, { 'label': 'zombies', 'data': zombie_tally, 'color': 'rgb(0, 128, 0)' }, ]
def clean_email(self): """Ensure that a user does not register twice for the same game.""" email = self.cleaned_data['email'] # Check both username and email because we're using both # fields for the same purpose... slice is there because # Django's builtin username field has a limit of 30 # characters. if Player.current_players().filter( Q(user__username=email[:30]) | Q(user__email=email) ).exists(): raise ValidationError(self.error_messages['duplicate_user']) return email
def json_get_all_names_and_emails(request): """A function that displays every players name and email in the current game. """ # Check out HVZ/main/models.py for helper functions relating to Players. # Player.current_players() returns all Players in the current Game. emails = [(str(p.user.first_name) + " " + str(p.user.last_name), p.mailbox) for p in Player.current_players()] # json.dumps creates a string from a Python object. You can then # read the string and convert it into an Objective-C data # structure using NSJSONSerialization in Objective-C. json_data = json.dumps(emails) return HttpResponse(json_data, content_type="application/json")
def legal_teams(user): if not user: return False if user.is_staff: return settings.VERBOSE_TEAMS.items() try: player = Player.user_to_player(user) except Player.DoesNotExist: return [] return ( (player.team, settings.VERBOSE_TEAMS[player.team]), ('B', settings.VERBOSE_TEAMS['B']), )
def legal_teams(user): if not user: return False if user.is_staff: return settings.VERBOSE_TEAMS.items() + Player.objects.values('clan') try: player = Player.user_to_player(user) except Player.DoesNotExist: return [] return ( (player.team, settings.VERBOSE_TEAMS[player.team]), (player.clan, player.clan), ('B', settings.VERBOSE_TEAMS['B']), )
def json_get_all_emails(request): """A function that displays all emails. You should replace this with one you actually want. """ # Check out HVZ/main/models.py for helper functions relating to Players. # Player.current_players() returns all Players in the current Game. emails = [p.user.email for p in Player.current_players()] # json.dumps creates a string from a Python object. You can then # read the string and convert it into an Objective-C data # structure using NSJSONSerialization in Objective-C. json_data = json.dumps(emails) return HttpResponse(json_data, content_type="application/json")
def may_view_forum(self, user, forum): """Players should not be able to access the other team's forums.""" # Check if the forum allows both teams. if forum.name == settings.VERBOSE_TEAMS['B']: return super(ForumPermissionHandler, self).may_view_forum(user, forum) # Compare the forum's name to the player's team. try: team = Player.user_to_player(user).team except Player.DoesNotExist: return False vb_team = settings.VERBOSE_TEAMS[team] if forum.name != vb_team: return False return super(ForumPermissionHandler, self).may_view_forum(user, forum)
def raw_serialization(self, context): game = Game.nearest_game() t0, tf = time_endpoints(game) players = Player.current_players().all() meals = Meal.objects.select_related('eaten').all() eaten_zombies = set([m.eaten for m in meals]) ozs = [p for p in players if p.team == 'Z' and p not in eaten_zombies] num_zombies = len(ozs) num_humans = len(players) - num_zombies human_tally = [] zombie_tally = [] meals_vs_hours = meals_per_hour(game, self.get_queryset()) for hour in xrange(len(meals_vs_hours)): t = t0 + timedelta(hours=hour) # Stop the graph at the current time if t > settings.NOW(): break meal_count = meals_vs_hours[hour] num_humans -= meal_count num_zombies += meal_count human_tally.append([json_format_time(t), num_humans]) zombie_tally.append([json_format_time(t), num_zombies]) if not human_tally: human_tally = [[json_format_time(t0), num_humans]] if not zombie_tally: zombie_tally = [[json_format_time(t0), num_zombies]] return [ {'label': 'humans', 'data': human_tally, 'color': 'rgb(128, 0, 0)'}, {'label': 'zombies', 'data': zombie_tally, 'color': 'rgb(0, 128, 0)'}, ]
def raw_serialization(self, context): self.players = Player.current_players().filter(team='Z').select_related('user') self.names = {p: p.user.get_full_name() for p in self.players} self.meals = (Meal.objects.filter(eater__game=Game.nearest_game()) .select_related('eater', 'eaten')) self.possible_ozs = set(self.players) self.children = defaultdict(list) for m in self.meals: if m.eaten not in self.players: continue self.children[m.eater].append(m.eaten) self.possible_ozs.remove(m.eaten) ozs = [p for p in self.players if p in self.possible_ozs] return { "name": "Subject Zero", "children": map(self.traverse, ozs), }
def json_get_all_graduation_years(request): """A pretty useless function that displays all graduation years. You should replace this with one you actually want. """ # Check out HVZ/main/models.py for helper functions relating to Players. # Player.current_players() returns all Players in the current Game. years = Player.logged_in_player(request).team # json.dumps creates a string from a Python object. You can then # read the string and convert it into an Objective-C data # structure using NSJSONSerialization in Objective-C. json_data = json.dumps(years) return HttpResponse( json_data, content_type="application/json" )
def raw_serialization(self, context): self.players = Player.current_players().filter( team='Z').select_related('user') self.names = {p: p.user.get_full_name() for p in self.players} self.meals = (Meal.objects.filter( eater__game=Game.nearest_game()).select_related('eater', 'eaten')) self.possible_ozs = set(self.players) self.children = defaultdict(list) for m in self.meals: if m.eaten not in self.players: continue self.children[m.eater].append(m.eaten) self.possible_ozs.remove(m.eaten) ozs = [p for p in self.players if p in self.possible_ozs] return { "name": "Subject Zero", "children": map(self.traverse, ozs), }
class DonateForm(forms.Form): receiver = forms.ModelChoiceField( Player.current_players().filter(team="Z"), required=True, ) numberOfMeals = forms.IntegerField( required=True, label="Number of Brains", ) def __init__(self, *args, **kwargs): super(DonateForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(DonateForm, self).clean() if not 'receiver' in cleaned_data: raise forms.ValidationError( "You must specify a person to receive your brains!") if not 'numberOfMeals' in cleaned_data: raise forms.ValidationError( "You must specify a number of brains to donate!") receivingPlayer = cleaned_data['receiver'] if not receivingPlayer.team == "Z": raise forms.ValidationError( "You somehow donated brains to a Human! They don't want your brains! Yet..." ) num_meals = cleaned_data['numberOfMeals'] if num_meals <= 0: raise forms.ValidationError( "You must donate a positive number of brains!") return cleaned_data
def inject_current_player(request): try: player = Player.user_to_player(request.user) except (Player.DoesNotExist, Game.DoesNotExist): player = None return {'player': player}
def as_player(user): try: return Player.user_to_player(user) except Player.DoesNotExist: return ""
def get_queryset(self): return Player.current_players()
def human_with_code(feedcode): """Ensure the feedcode corresponds to a currently-playing Human.""" if not Player.current_players().filter(team="H", feed=feedcode).exists(): raise ValidationError( "{} doesn't correspond to a playing human!".format(feedcode))
def as_player(user): try: return Player.user_to_player(user) except: return ""