Esempio n. 1
0
def view_game(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    can_view_scenario = False
    my_invitation = None
    if request.user.is_authenticated:
        my_invitation = get_object_or_none(
            request.user.game_invite_set.filter(relevant_game=game_id))
    if request.user.has_perm("view_scenario", game.scenario):
        can_view_scenario = True
    invite_form = None
    can_edit = game.player_can_edit(request.user)
    if can_edit and game.is_scheduled():
        initial_data = {"message": game.hook}
        invite_form = CustomInviteForm(initial=initial_data)
    nsfw_blocked = game.is_nsfw and (
        request.user.is_anonymous
        or not request.user.profile.view_adult_content)
    reason_cannot_rsvp = game.reason_player_cannot_rsvp(request.user)
    can_rsvp = not reason_cannot_rsvp

    gametime_url = None if not my_invitation or not game.gametime_url else game.gametime_url
    context = {
        'game': game,
        'can_view_scenario': can_view_scenario,
        'my_invitation': my_invitation,
        'invite_form': invite_form,
        'can_edit': can_edit,
        'can_rsvp': can_rsvp,
        'reason_cannot_rsvp': reason_cannot_rsvp,
        'nsfw_blocked': nsfw_blocked,
        'gametime_url': gametime_url,
    }
    return render(request, 'games/view_game_pages/view_game.html', context)
 def player_is_only_leader(self, player):
     membership = get_object_or_none(
         self.cellmembership_set.filter(member_player=player))
     if not membership:
         return False
     return membership.role == ROLE[0][0] and get_queryset_size(
         self.cellmembership_set.filter(role=ROLE[0][0])) == 1
Esempio n. 3
0
 def not_attending(self, player):
     invite = get_object_or_none(self.game_invite_set.filter(invited_player=player))
     if invite:
         attendance = invite.attendance
         if attendance:
             attendance.delete()
         invite.delete()
 def get_improvement(self):
     return get_object_or_none(
         Reward,
         rewarded_player=self.game_attendance.get_player(),
         relevant_game=self.game_attendance.relevant_game,
         is_void=False,
         is_journal=True)
Esempio n. 5
0
def accept_invite(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    if not game.player_can_rsvp(request.user):
        raise PermissionDenied(game.reason_player_cannot_rsvp(request.user))
    invite = get_object_or_none(
        request.user.game_invite_set.filter(relevant_game=game.id))
    if request.method == 'POST':
        if not invite:
            # player self-invite
            invite = Game_Invite(invited_player=request.user,
                                 relevant_game=game)
            if game.scenario in request.user.scenario_set.all():
                invite.as_ringer = True
        form = make_accept_invite_form(invite)(request.POST)
        if form.is_valid():
            game_attendance = invite.attendance
            with transaction.atomic():
                invite.save()
                if game_attendance:
                    game_attendance.attending_character = form.cleaned_data[
                        'attending_character']
                    game_attendance.save()
                else:
                    game_attendance = Game_Attendance(
                        attending_character=form.
                        cleaned_data['attending_character'],
                        relevant_game=game,
                    )
                    game_attendance.save()
                    invite.is_declined = False
                    invite.attendance = game_attendance
                    invite.save()
                    if invite.as_ringer and not form.cleaned_data[
                            'attending_character']:
                        #Reveal scenario to ringer
                        game.scenario.played_discovery(request.user)
            return HttpResponseRedirect(
                reverse('games:games_view_game', args=(game.id, )))
        else:
            print(form.errors)
            return None
    else:
        can_view_scenario = False
        if request.user.has_perm("view_scenario", game.scenario):
            can_view_scenario = True
        # Build a accept form.
        if not invite:
            # if game is open for self-invites, make a temp invite that we don't save so we can make a form
            invite = Game_Invite(invited_player=request.user,
                                 relevant_game=game)
            if game.scenario in request.user.scenario_set.all():
                invite.as_ringer = True
        form = make_accept_invite_form(invite)
        context = {
            'form': form,
            'game': game,
            'invite': invite,
            'can_view_scenario': can_view_scenario,
        }
        return render(request, 'games/accept_invite.html', context)
Esempio n. 6
0
 def reason_player_cannot_rsvp(self, player):
     if not player.is_authenticated or player.is_anonymous:
         return "You must log in to accept this Game invite"
     if self.gm == player:
         return "GMs cannot RSVP to their own Games"
     if player.is_superuser:
         return None
     if hasattr(self,
                "max_rsvp") and self.max_rsvp and self.get_attended_players(
                ).count() >= self.max_rsvp:
         return "This Game is full"
     if self.invitation_mode == CLOSED or not self.is_scheduled():
         return "This Game is closed for RSVPs."
     if self.is_nsfw and not player.profile.view_adult_content:
         return "This Game is marked for adults. Your content settings do not allow you to participate."
     player_invitation = get_object_or_none(
         player.game_invite_set.filter(relevant_game=self.id))
     if player_invitation:
         return None
     if self.invitation_mode == INVITE_ONLY:
         return "This Game only allows those with an invitation to RSVP."
     if self.invitation_mode == WORLD_MEMBERS:
         if not self.cell.get_player_membership(player):
             return "This Game only allows those who are a member of its World to RSVP without an invite."
         else:
             return None
     # ANYONE case
     return None
Esempio n. 7
0
 def dispatch(self, *args, **kwargs):
     self.character = get_object_or_404(Character, id=self.kwargs['character_id'])
     self.__check_permissions()
     self.cover = get_object_or_none(JournalCover, character=self.character)
     if self.cover:
         self.initial = {
             "title": self.cover.title,
             "content": self.cover.content,
         }
     return super().dispatch(*args, **kwargs)
Esempio n. 8
0
 def invitePlayer(self, player, text):
     extant_invite = get_object_or_none(
         self.cellinvite_set.filter(invited_player=player))
     membership = get_object_or_none(
         self.cellmembership_set.filter(member_player=player))
     if membership:
         membership.delete()
     if extant_invite:
         if extant_invite.is_declined:
             extant_invite.is_declined = False
             extant_invite.save()
             return extant_invite
     else:
         invite = CellInvite(
             relevant_cell=self,
             invited_player=player,
             invite_text=text,
         )
         invite.save()
         return invite
 def removePlayer(self, player):
     membership = get_object_or_none(
         self.cellmembership_set.filter(member_player=player))
     if not membership:
         raise ValueError("player not in cell")
     if self.player_is_only_leader(player):
         raise ValueError("Cannot remove only leader")
     membership = self.cellmembership_set.get(member_player=player)
     membership.remove_user_from_all_groups()
     membership.remove_characters_from_cell()
     membership.delete()
Esempio n. 10
0
def view_scenario(request, scenario_id, game_id=None):
    scenario = get_object_or_404(Scenario, id=scenario_id)
    if not scenario.player_can_view(
            request.user) and not scenario.player_discovered(request.user):
        raise PermissionDenied(
            "You don't have permission to view this scenario")
    show_spoiler_warning = scenario.is_public() \
                           and not (request.user.is_authenticated and scenario.player_discovered(request.user)) \
                            or scenario.is_spoilable_for_player(request.user)

    if request.method == 'POST':
        form = GameFeedbackForm(request.POST)
        if form.is_valid() and game_id:
            game = get_object_or_none(Game, id=game_id)
            if game and game.gm.id == request.user.id and str(
                    game.scenario.id) == scenario_id:
                with transaction.atomic():
                    game = get_object_or_404(Game, id=game_id)
                    if game.gm.id == request.user.id:
                        game.scenario_notes = form.cleaned_data[
                            'scenario_notes']
                        game.save()
            else:
                raise ValueError("Invalid Game for feedback")
        return HttpResponseRedirect(
            reverse('games:games_view_scenario', args=(scenario.id, )))
    else:
        game_feedback = None
        games_run = Game.objects.filter(
            gm_id=request.user.id,
            scenario_id=scenario.id).order_by("end_time").all()
        games_run = [
            x for x in games_run if not x.is_scheduled() and not x.is_active()
        ]
        games_run_no_feedback = Game.objects.filter(gm_id=request.user.id,
                                                    scenario_id=scenario.id,
                                                    scenario_notes=None).all()
        games_run_no_feedback = [
            x for x in games_run_no_feedback
            if not x.is_scheduled() and not x.is_active()
        ]
        if games_run_no_feedback:
            game_feedback = GameFeedbackForm()
        context = {
            'show_spoiler_warning': show_spoiler_warning,
            'scenario': scenario,
            'games_run': games_run,
            'games_run_no_feedback': games_run_no_feedback,
            'game_feedback_form': game_feedback,
        }
        return render(request, 'games/view_scenario.html', context)
Esempio n. 11
0
 def ban_player(self, player, reason):
     membership = get_object_or_none(
         self.cellmembership_set.filter(member_player=player))
     if not membership:
         raise ValueError("player not in cell")
     if self.player_is_only_leader(player):
         raise ValueError("Cannot remove only leader")
     membership = self.cellmembership_set.get(member_player=player)
     membership.remove_user_from_all_groups()
     membership.remove_characters_from_cell()
     membership.is_banned = True
     membership.reason_banned = reason
     membership.date_banned = timezone.now()
     membership.save()
Esempio n. 12
0
 def addPlayer(self, player, role):
     if self.get_player_membership(player):
         raise ValueError("player already in cell")
     membership = CellMembership(
         relevant_cell=self,
         member_player=player,
         role=role[0],
     )
     membership.save()
     invite = get_object_or_none(
         self.cellinvite_set.filter(invited_player=player))
     if invite:
         invite.membership = membership
         invite.save()
     return membership
 class SelectArtifactForm(forms.Form):
     initial_artifact = None
     if existing_power and existing_power.crafting_type == CRAFTING_SIGNATURE:
         initial_artifact = get_object_or_none(
             existing_power.artifactpowerfull_set.filter(
                 relevant_artifact__is_signature=True))
     if existing_character:
         queryset = existing_character.artifact_set.filter(
             cell__isnull=True,
             crafting_character=existing_character,
             is_signature=True)
     elif existing_power and existing_power.owner:
         queryset = existing_power.owner.artifact_set.filter(
             cell__isnull=True,
             crafting_character__isnull=True,
             is_signature=True)
     elif user and user.is_authenticated:
         queryset = user.artifact_set.filter(
             cell__isnull=True,
             crafting_character__isnull=True,
             is_signature=True)
     else:
         queryset = Artifact.objects.none()
     selected_artifact = forms.ModelChoiceField(
         queryset=queryset,
         initial=initial_artifact,
         required=False,
         empty_label="Create New Artifact",
         label="Attach to existing Legendary Artifact?",
         widget=forms.Select(attrs={
             'v-model': 'selectedItem',
             "@input": "changeSelectedItem",
         }))
     item_name = forms.CharField(
         required=False,
         max_length=450,
         help_text="The name of the Legendary Artifact",
         widget=forms.TextInput(attrs={
             'v-model': 'sigItemName',
         }))
     item_description = forms.CharField(
         required=False,
         max_length=5000,
         help_text="(Optional) A physical description of the Artifact",
         widget=forms.TextInput(attrs={
             'v-model': 'sigItemDescription',
         }))
Esempio n. 14
0
def view_cell(request, cell_id):
    cell = get_object_or_404(Cell, id=cell_id)
    #TODO: View permissions? Private cells?
    can_manage_memberships = cell.player_can_manage_memberships(request.user)
    can_edit_world = cell.player_can_edit_world(request.user)
    user_membership = None
    invite = None
    if request.user.is_authenticated:
        invite = get_object_or_none(
            cell.open_invitations().filter(invited_player=request.user))
        user_membership = cell.get_player_membership(request.user)
        if not request.user.profile.confirmed_agreements:
            return HttpResponseRedirect(reverse('profiles:profiles_terms'))
    can_edit_characters = cell.player_can_edit_characters(request.user)
    can_administer = cell.player_can_admin(request.user)
    can_manage_games = cell.player_can_manage_games(request.user)
    memberships_and_characters = ()
    for role in ROLE:
        for membership in cell.cellmembership_set.filter(role=role[0]):
            characters = ()
            for character in membership.member_player.character_set.filter(
                    cell=cell, is_deleted=False):
                if not character.is_dead():
                    characters = characters + (character, )
            memberships_and_characters = memberships_and_characters + ((
                membership,
                characters,
            ), )
    upcoming_games = cell.game_set.filter(status=GAME_STATUS[0][0])
    completed_games = cell.game_set\
        .exclude(Q(status = GAME_STATUS[0][0]) | Q(status = GAME_STATUS[1][0]) | Q(status = GAME_STATUS[4][0]))\
        .order_by("end_time").all()

    context = {
        'cell': cell,
        'can_edit_world': can_edit_world,
        'can_manage_memberships': can_manage_memberships,
        'can_edit_characters': can_edit_characters,
        'user_membership': user_membership,
        'can_administer': can_administer,
        'can_manage_games': can_manage_games,
        'memberships_and_characters': memberships_and_characters,
        'upcoming_games': upcoming_games,
        'completed_games': completed_games,
        'invite': invite,
    }
    return render(request, 'cells/view_cell.html', context)
Esempio n. 15
0
def decline_invite(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    if game.is_scheduled():
        invite = get_object_or_none(
            request.user.game_invite_set.filter(relevant_game=game))
        if not invite:
            return HttpResponseRedirect(
                reverse('games:games_view_game', args=(game.id, )))
        if request.user == invite.invited_player:
            invite.is_declined = True
            if invite.attendance:
                invite.attendance.delete()
                invite.attendance = None
            with transaction.atomic():
                invite.save()
    return HttpResponseRedirect(
        reverse('games:games_view_game', args=(game.id, )))
Esempio n. 16
0
 def invitePlayer(self, player, text):
     extant_invite = get_object_or_none(
         self.cellinvite_set.filter(invited_player=player))
     if extant_invite:
         if extant_invite.is_declined:
             extant_invite.is_declined = False
             extant_invite.save()
             return extant_invite
         else:
             raise ValueError("Cannot invite someone already invited")
     else:
         invite = CellInvite(
             relevant_cell=self,
             invited_player=player,
             invite_text=text,
         )
         invite.save()
         return invite
Esempio n. 17
0
def rsvp_invite(request, cell_id, secret_key=None, accept=None):
    if not request.user.is_authenticated:
        raise PermissionDenied(
            "You must be logged in to RSVP to a Cell invitation")
    if accept:
        is_accepted = accept == 'y'
    else:
        is_accepted = False
    cell = get_object_or_404(Cell, id=cell_id)
    if cell.get_player_membership(request.user):
        return HttpResponseRedirect(
            reverse('cells:cells_view_cell', args=(cell.id, )))
    invite = get_object_or_none(
        cell.open_invitations().filter(invited_player=request.user))
    if not invite:
        if not cell.allow_self_invites and (
                not secret_key
                or not cell.invite_link_secret_key == secret_key):
            raise PermissionDenied(
                "You have not been invited to this World or your invite link has expired. Ask for a new one."
            )
    if request.method == 'POST':
        form = RsvpForm(request.POST)
        if form.is_valid():
            with transaction.atomic():
                if is_accepted and invite:
                    invite.accept()
                elif is_accepted and not invite:
                    cell.addPlayer(request.user, ROLE[2])
                elif invite:
                    invite.reject()
            return HttpResponseRedirect(
                reverse('cells:cells_view_cell', args=(cell.id, )))
        else:
            print(form.errors)
            return None
    else:
        form = RsvpForm()
        context = {
            'form': form,
            'cell': cell,
            'secret_key': secret_key,
        }
        return render(request, 'cells/rsvp_invite.html', context)
Esempio n. 18
0
def view_game(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    can_view_scenario = False
    my_invitation = None
    if request.user.is_authenticated:
        my_invitation = get_object_or_none(
            request.user.game_invite_set.filter(relevant_game=game_id))
    if request.user.has_perm("view_scenario", game.scenario):
        can_view_scenario = True
    invite_form = None
    if request.user.has_perm('edit_game', game) and game.is_scheduled():
        initial_data = {"message": game.hook}
        invite_form = CustomInviteForm(initial=initial_data)
    context = {
        'game': game,
        'can_view_scenario': can_view_scenario,
        'my_invitation': my_invitation,
        'invite_form': invite_form,
    }
    return render(request, 'games/view_game_pages/view_game.html', context)
Esempio n. 19
0
def view_character(request, character_id, secret_key=None):
    character = get_object_or_404(Character, id=character_id)
    if character.player and secret_key:
        return HttpResponseRedirect(
            reverse('characters:characters_view', args=(character_id, )))
    if not character.player_can_view(request.user):
        raise PermissionDenied(
            "You do not have permission to view this Character")
    if request.user.is_authenticated and not request.user.profile.confirmed_agreements:
        return HttpResponseRedirect(reverse('profiles:profiles_terms'))
    secret_key_valid = False
    if secret_key:
        secret_key_valid = character.is_editable_with_key(secret_key)
    else:
        secret_key = ""
    user_can_edit = (request.user.is_authenticated
                     and character.player_can_edit(
                         request.user)) or secret_key_valid
    if not character.stats_snapshot:
        context = {"character": character, "user_can_edit": user_can_edit}
        return render(request, 'characters/legacy_character.html', context)

    completed_games = [(x.relevant_game.end_time, "game", x)
                       for x in character.completed_games()
                       ]  # completed_games() does ordering
    character_edit_history = [
        (x.created_time, "edit", x)
        for x in character.contractstats_set.filter(
            is_snapshot=False).order_by("created_time").all()[1:]
    ]
    exp_rewards = [(x.created_time, "exp_reward", x)
                   for x in character.experiencereward_set.filter(
                       is_void=False).order_by("created_time").all()]
    events_by_date = list(
        merge(completed_games, character_edit_history, exp_rewards))
    timeline = defaultdict(list)
    for event in events_by_date:
        if event[1] == "edit":
            phrases = event[2].get_change_phrases()
            if len(phrases):
                timeline[event[0].strftime("%d %b %Y")].append(
                    (event[1], phrases))
        else:
            timeline[event[0].strftime("%d %b %Y")].append(
                (event[1], event[2]))

    char_ability_values = character.stats_snapshot.abilityvalue_set.order_by(
        "relevant_ability__name").all()
    ability_value_by_id = {}
    char_value_ids = [x.relevant_ability.id for x in char_ability_values]
    primary_zero_values = [(x.name, x, 0) for x in Ability.objects.filter(
        is_primary=True).order_by("name").all() if x.id not in char_value_ids]
    all_ability_values = []
    for x in char_ability_values:
        all_ability_values.append(
            (x.relevant_ability.name, x.relevant_ability, x.value))
        ability_value_by_id[x.relevant_ability.id] = x.value
    ability_value_by_name = list(merge(primary_zero_values,
                                       all_ability_values))
    unspent_experience = character.unspent_experience()
    exp_earned = character.exp_earned()
    exp_cost = character.exp_cost()

    equipment_form = EquipmentForm()
    bio_form = BioForm()

    num_journal_entries = character.num_journals if character.num_journals else 0
    latest_journals = []
    if num_journal_entries > 0:
        journal_query = Journal.objects.filter(
            game_attendance__attending_character=character.id).order_by(
                '-created_date')
        if request.user.is_anonymous or not request.user.profile.view_adult_content:
            journal_query = journal_query.exclude(is_nsfw=True)
        journals = journal_query.all()
        for journal in journals:
            if len(latest_journals) > 2:
                break
            if journal.player_can_view(request.user):
                latest_journals.append(journal)

    journal_cover = get_object_or_none(JournalCover, character=character.id)
    next_entry = get_characters_next_journal_credit(
        character) if user_can_edit else None

    show_more_home_games_warning = character.number_completed_games() > 3 \
                                   and (character.number_completed_games_in_home_cell() < character.number_completed_games_out_of_home_cell())
    available_gift = character.unspent_rewards().count() > 0
    circumstance_form = None
    condition_form = None
    artifact_form = None
    world_element_initial_cell = character.world_element_initial_cell()
    world_element_cell_choices = None
    if user_can_edit:
        # We only need these choices if the user can edit, both for forms and for char sheet.
        world_element_cell_choices = character.world_element_cell_choices()
        circumstance_form = make_world_element_form(
            world_element_cell_choices, world_element_initial_cell)
        condition_form = make_world_element_form(world_element_cell_choices,
                                                 world_element_initial_cell)
        artifact_form = make_world_element_form(world_element_cell_choices,
                                                world_element_initial_cell)

    artifacts = get_world_element_default_dict(world_element_cell_choices)
    for artifact in character.artifact_set.all():
        artifacts[artifact.cell].append(artifact)
    artifacts = dict(artifacts)

    circumstances = get_world_element_default_dict(world_element_cell_choices)
    for circumstance in character.circumstance_set.all():
        circumstances[circumstance.cell].append(circumstance)
    circumstances = dict(circumstances)

    conditions = get_world_element_default_dict(world_element_cell_choices)
    for condition in character.condition_set.all():
        conditions[condition.cell].append(condition)
    conditions = dict(conditions)

    assets = character.stats_snapshot.assetdetails_set.all()
    liabilities = character.stats_snapshot.liabilitydetails_set.all()
    physical_attributes = character.get_attributes(is_physical=True)
    mental_attributes = character.get_attributes(is_physical=False)
    attribute_value_by_id = {}
    for attr in physical_attributes:
        attribute_value_by_id[
            attr.relevant_attribute.id] = attr.val_with_bonuses()
    for attr in mental_attributes:
        attribute_value_by_id[
            attr.relevant_attribute.id] = attr.val_with_bonuses()
    context = {
        'character': character,
        'user_can_edit': user_can_edit,
        'health_display': character.get_health_display(),
        'ability_value_by_name': ability_value_by_name,
        'ability_value_by_id': ability_value_by_id,
        'physical_attributes': physical_attributes,
        'mental_attributes': mental_attributes,
        'attribute_value_by_id': attribute_value_by_id,
        'timeline': dict(timeline),
        'tutorial': get_object_or_404(CharacterTutorial),
        'battle_scar_form': BattleScarForm(),
        'trauma_form': TraumaForm(prefix="trauma"),
        'injury_form': InjuryForm(request.POST, prefix="injury"),
        'exp_cost': exp_cost,
        'exp_earned': exp_earned,
        'unspent_experience': unspent_experience,
        'equipment_form': equipment_form,
        'bio_form': bio_form,
        'secret_key': secret_key,
        'secret_key_valid': secret_key_valid,
        'num_journal_entries': num_journal_entries,
        'journal_cover': journal_cover,
        'next_entry': next_entry,
        'latest_journals': latest_journals,
        'show_more_home_games_warning': show_more_home_games_warning,
        'available_gift': available_gift,
        'circumstance_form': circumstance_form,
        'condition_form': condition_form,
        'artifact_form': artifact_form,
        'artifacts_by_cell': artifacts,
        'conditions_by_cell': conditions,
        'circumstances_by_cell': circumstances,
        'initial_cell': world_element_initial_cell,
        'assets': assets,
        'liabilities': liabilities,
    }
    return render(request, 'characters/view_pages/view_character.html',
                  context)
Esempio n. 20
0
def view_character(request, character_id, secret_key = None):
    character = get_object_or_404(Character, id=character_id)
    if character.player and secret_key:
        return HttpResponseRedirect(reverse('characters:characters_view', args=(character_id,)))
    if not character.player_can_view(request.user):
        raise PermissionDenied("You do not have permission to view this Character")
    if request.user.is_authenticated and not request.user.profile.confirmed_agreements:
            return HttpResponseRedirect(reverse('profiles:profiles_terms'))
    secret_key_valid = False
    if secret_key:
        secret_key_valid = character.is_editable_with_key(secret_key)
    else:
        secret_key = ""
    user_can_edit = (request.user.is_authenticated and character.player_can_edit(request.user)) or secret_key_valid
    if not character.stats_snapshot:
        context={"character": character,
                 "user_can_edit": user_can_edit}
        return render(request, 'characters/legacy_character.html', context)

    completed_games = [(x.relevant_game.end_time, "game", x) for x in character.completed_games()] # completed_games() does ordering
    character_edit_history = [(x.created_time, "edit", x) for x in
                              character.contractstats_set.filter(is_snapshot=False).order_by("created_time").all()[1:]]
    exp_rewards = [(x.created_time, "exp_reward", x) for x in character.experiencereward_set.filter(is_void=False).order_by("created_time").all()]
    events_by_date = list(merge(completed_games, character_edit_history, exp_rewards))
    timeline = defaultdict(list)
    for event in events_by_date:
        timeline[event[0].strftime("%d %b %Y")].append((event[1], event[2]))

    char_ability_values = character.stats_snapshot.abilityvalue_set.order_by("relevant_ability__name").all()
    char_value_ids = [x.relevant_ability.id for x in char_ability_values]
    primary_zero_values = [(x.name, x, 0) for x in Ability.objects.filter(is_primary=True).order_by("name").all()
                 if x.id not in char_value_ids]
    all_ability_values =[(x.relevant_ability.name, x.relevant_ability, x.value) for x in char_ability_values]
    ability_value_by_name = list(merge(primary_zero_values, all_ability_values))
    unspent_experience = character.unspent_experience()
    exp_earned = character.exp_earned()
    exp_cost = character.exp_cost()

    equipment_form = EquipmentForm()
    bio_form = BioForm()

    num_journal_entries = Journal.objects.filter(game_attendance__attending_character=character.id).count()
    journal_cover = get_object_or_none(JournalCover, character=character.id)
    next_entry = get_characters_next_journal_credit(character) if user_can_edit else None
    context = {
        'character': character,
        'user_can_edit': user_can_edit,
        'health_display': character.get_health_display(),
        'ability_value_by_name': ability_value_by_name,
        'physical_attributes': character.get_attributes(is_physical=True),
        'mental_attributes': character.get_attributes(is_physical=False),
        'timeline': dict(timeline),
        'tutorial': get_object_or_404(CharacterTutorial),
        'battle_scar_form': BattleScarForm(),
        'trauma_form': TraumaForm(prefix="trauma"),
        'injury_form': InjuryForm(request.POST, prefix="injury"),
        'exp_cost': exp_cost,
        'exp_earned': exp_earned,
        'unspent_experience': unspent_experience,
        'equipment_form': equipment_form,
        'bio_form': bio_form,
        'secret_key': secret_key,
        'secret_key_valid': secret_key_valid,
        'num_journal_entries': num_journal_entries,
        'journal_cover': journal_cover,
        'next_entry': next_entry,
    }
    return render(request, 'characters/view_pages/view_character.html', context)
Esempio n. 21
0
def accept_invite(request, game_id):
    if not request.user.is_authenticated or request.user.is_anonymous:
        raise PermissionDenied("You must log in to accept this Game invite")
    game = get_object_or_404(Game, id=game_id)
    if not game.is_scheduled(
    ) or game.creator.id == request.user.id or game.gm.id == request.user.id:
        raise PermissionDenied(
            "This Game has already started, or you're the GM!")
    invite = get_object_or_none(
        request.user.game_invite_set.filter(relevant_game=game))
    if not invite and not game.open_invitations:
        raise PermissionDenied(
            "This is awkward. . . You, uh, haven't been invited to this Game")
    if request.method == 'POST':
        if not invite:
            # player self-invite
            invite = Game_Invite(invited_player=request.user,
                                 relevant_game=game)
            if game.scenario in request.user.scenario_set.all():
                invite.as_ringer = True
        form = make_accept_invite_form(invite)(request.POST)
        if form.is_valid():
            game_attendance = invite.attendance
            with transaction.atomic():
                invite.save()
                if game_attendance:
                    game_attendance.attending_character = form.cleaned_data[
                        'attending_character']
                    game_attendance.save()
                else:
                    game_attendance = Game_Attendance(
                        attending_character=form.
                        cleaned_data['attending_character'],
                        relevant_game=game,
                    )
                    game_attendance.save()
                    invite.is_declined = False
                    invite.attendance = game_attendance
                    invite.save()
                    if invite.as_ringer and not form.cleaned_data[
                            'attending_character']:
                        #Reveal scenario to ringer
                        game.scenario.played_discovery(request.user)
            return HttpResponseRedirect(
                reverse('games:games_view_game', args=(game.id, )))
        else:
            print(form.errors)
            return None
    else:
        can_view_scenario = False
        if request.user.has_perm("view_scenario", game.scenario):
            can_view_scenario = True
        # Build a accept form.
        if not invite:
            # if game is open for self-invites, make a temp invite that we don't save so we can make a form
            invite = Game_Invite(invited_player=request.user,
                                 relevant_game=game)
            if game.scenario in request.user.scenario_set.all():
                invite.as_ringer = True
        form = make_accept_invite_form(invite)
        context = {
            'form': form,
            'game': game,
            'invite': invite,
            'can_view_scenario': can_view_scenario,
        }
        return render(request, 'games/accept_invite.html', context)
Esempio n. 22
0
 def get_player_membership(self, player):
     return get_object_or_none(
         self.cellmembership_set.filter(member_player=player))
Esempio n. 23
0
 def discovery_for_player(self, player):
     return get_object_or_none(Scenario_Discovery,
                               relevant_scenario=self,
                               discovering_player=player)
Esempio n. 24
0
 def get_permissions_for_role(self, role):
     return get_object_or_none(PermissionsSettings,
                               relevant_cell=self,
                               role=role)
Esempio n. 25
0
def view_cell(request, cell_id):
    cell = get_object_or_404(Cell, id=cell_id)
    user_membership = None
    invite = None
    can_manage_memberships = None
    can_edit_world = None
    can_edit_characters = None
    can_administer = None
    can_manage_games = None
    can_post_world_events = None
    can_gm = None
    my_cell_contractors = None
    if request.user.is_authenticated:
        if not request.user.profile.confirmed_agreements:
            return HttpResponseRedirect(reverse('profiles:profiles_terms'))
        invite = get_object_or_none(
            cell.open_invitations().filter(invited_player=request.user))
        user_membership = cell.get_player_membership(request.user)
        can_manage_memberships = cell.player_can_manage_memberships(
            request.user)
        can_edit_world = cell.player_can_edit_world(request.user)
        can_edit_characters = cell.player_can_edit_characters(request.user)
        can_administer = cell.player_can_admin(request.user)
        can_manage_games = cell.player_can_manage_games(request.user)
        can_post_world_events = cell.player_can_post_world_events(request.user)
        can_gm = cell.player_can_run_games(request.user)
        my_cell_contractors = request.user.character_set.filter(
            cell=cell, is_deleted=False)

    memberships_and_characters = ()
    for role in ROLE:
        for membership in cell.cellmembership_set.filter(role=role[0]):
            characters = ()
            for character in membership.member_player.character_set.filter(
                    cell=cell, is_deleted=False):
                if not character.is_dead():
                    characters = characters + (character, )
            memberships_and_characters = memberships_and_characters + ((
                membership,
                characters,
            ), )
    upcoming_games = cell.game_set.filter(status=GAME_STATUS[0][0])
    completed_games = cell.completed_games()
    world_events = WorldEvent.objects.filter(
        parent_cell=cell).order_by("-created_date").all()

    can_view_community_link = cell.is_community_link_public or user_membership
    community_link = cell.community_link if can_view_community_link else None

    journal_query = Journal.objects.filter(game_attendance__attending_character__private=False)\
        .filter(game_attendance__relevant_game__cell=cell)
    if request.user.is_anonymous:
        journal_query.filter(contains_spoilers=False, is_nsfw=False)
    elif not request.user.profile.view_adult_content:
        journal_query.filter(is_nsfw=False)
    public_journals = journal_query.order_by('-created_date').all()[:20]
    max_journals_to_display = 20
    displayed_journals = []
    for journal in public_journals:
        if max_journals_to_display <= len(displayed_journals):
            break
        if journal.player_can_view(request.user):
            displayed_journals.append(journal)

    context = {
        'cell': cell,
        'can_edit_world': can_edit_world,
        'can_manage_memberships': can_manage_memberships,
        'can_edit_characters': can_edit_characters,
        'user_membership': user_membership,
        'can_administer': can_administer,
        'can_manage_games': can_manage_games,
        'can_post_world_events': can_post_world_events,
        'can_gm': can_gm,
        'memberships_and_characters': memberships_and_characters,
        'upcoming_games': upcoming_games,
        'completed_games': completed_games,
        'invite': invite,
        'my_cell_contractors': my_cell_contractors,
        'world_events': world_events,
        'community_link': community_link,
        'latest_journals': displayed_journals,
    }
    return render(request, 'cells/view_cell.html', context)
Esempio n. 26
0
 def get_reward(self):
     return get_object_or_none(Reward,
                               rewarded_player=self.get_player(),
                               relevant_game=self.relevant_game,
                               is_void=False)
Esempio n. 27
0
    def __get_context_data(self):
        if 'journal_id' in self.kwargs:
            journal = get_object_or_404(Journal, id=self.kwargs['journal_id'])
            character = journal.game_attendance.attending_character
            game_id = journal.game_attendance.relevant_game.id
        else:
            character = get_object_or_404(Character,
                                          id=self.kwargs['character_id'])
            game_id = self.kwargs[
                'game_id'] if 'game_id' in self.kwargs else None
        viewer_can_write = character.player_can_edit(self.request.user)
        completed_attendances = character.completed_games()
        cover = get_object_or_none(JournalCover, character=character)
        journal_pages = []
        cover_id = "journal_page_cover"
        journal_page = {
            "header": "cover",
            "id": cover_id,
            "empty": False,
            "cover": cover if cover else {
                "title": "",
                "content": ""
            },
        }
        journal_pages.append(journal_page)
        for i, attendance in enumerate(completed_attendances, start=1):
            if attendance.is_death():
                continue
            journal_page = {
                "header": roman.toRoman(i),
                "game": attendance.relevant_game,
                "id": "journal_page_{}".format(attendance.relevant_game.id),
                "game_journal": None,
                "downtime_journals": [],
                "empty": False,
            }
            journals = attendance.journal_set.filter(is_deleted=False)
            if journals.count() == 0:
                if viewer_can_write:
                    journal_page["empty"] = True
                    journal_pages.append(journal_page)
            else:
                game_journal = get_object_or_none(Journal,
                                                  game_attendance=attendance,
                                                  is_deleted=False,
                                                  is_downtime=False)
                if game_journal:
                    game_journal.inject_viewable(self.request.user)
                journal_page["game_journal"] = game_journal
                journal_page["downtime_journals"] = journals.filter(
                    is_downtime=True).order_by("created_date").all()
                for journal in journal_page["downtime_journals"]:
                    journal.inject_viewable(self.request.user)
                journal_pages.append(journal_page)
        death = character.real_death()
        if death:
            journal_page = {
                "header":
                "death",
                "game":
                death.game_attendance.relevant_game
                if hasattr(death, 'game_attendance') and death.game_attendance
                else None,
                "id":
                "journal_page_death",
                "game_journal":
                None,
                "downtime_journals": [],
                "empty":
                False,
                "death":
                death,
            }
            journal_pages.append(journal_page)

        prev_page = None
        for journal_page in journal_pages:
            if prev_page:
                prev_page['next_id'] = journal_page['id']
                journal_page['prev_id'] = prev_page['id']
            prev_page = journal_page
        num_journals_until_improvement = Journal.get_num_journals_until_improvement(
            character) if viewer_can_write else 0
        next_reward_is_improvement = num_journals_until_improvement <= 1
        context = {
            'view_game_id':
            "journal_page_{}".format(game_id) if game_id else cover_id,
            'character': character,
            'viewer_can_write': viewer_can_write,
            'journal_pages': journal_pages,
            'next_reward_is_improvement': next_reward_is_improvement,
            'num_journals_until_improvement': num_journals_until_improvement,
        }
        return context