예제 #1
0
def click_fatlink_view(request, token, fat_hash=None):
    fatlink = get_object_or_404(Fatlink, hash=fat_hash)

    if (timezone.now() - fatlink.fatdatetime) < datetime.timedelta(
            seconds=(fatlink.duration * 60)):

        character = EveCharacter.objects.get_character_by_id(
            token.character_id)

        if character:
            # get data
            c = token.get_esi_client(spec_file=SWAGGER_SPEC_PATH)
            location = c.Location.get_characters_character_id_location(
                character_id=token.character_id).result()
            ship = c.Location.get_characters_character_id_ship(
                character_id=token.character_id).result()
            location['solar_system_name'] = \
                c.Universe.get_universe_systems_system_id(system_id=location['solar_system_id']).result()[
                    'name']
            if location['station_id']:
                location['station_name'] = \
                    c.Universe.get_universe_stations_station_id(station_id=location['station_id']).result()['name']
            elif location['structure_id']:
                location['station_name'] = \
                    c.Universe.get_universe_structures_structure_id(structure_id=location['structure_id']).result()[
                        'name']
            else:
                location['station_name'] = "No Station"
            ship['ship_type_name'] = provider.get_itemtype(
                ship['ship_type_id']).name

            fat = Fat()
            fat.system = location['solar_system_name']
            fat.station = location['station_name']
            fat.shiptype = ship['ship_type_name']
            fat.fatlink = fatlink
            fat.character = character
            fat.user = request.user
            try:
                fat.full_clean()
                fat.save()
                messages.success(request, _('Fleet participation registered.'))
            except ValidationError as e:
                err_messages = []
                for errorname, message in e.message_dict.items():
                    err_messages.append(message[0])
                messages.error(request, ' '.join(err_messages))
        else:
            context = {
                'character_id': token.character_id,
                'character_name': token.character_name
            }
            return render(request,
                          'fleetactivitytracking/characternotexisting.html',
                          context=context)
    else:
        messages.error(request, _('FAT link has expired.'))
    return redirect('fatlink:view')
예제 #2
0
def click_fatlink_view(request, token, fat_hash=None):
    fatlink = get_object_or_404(Fatlink, hash=fat_hash)

    if (timezone.now() - fatlink.fatdatetime) < datetime.timedelta(seconds=(fatlink.duration * 60)):

        character = EveCharacter.objects.get_character_by_id(token.character_id)

        if character:
            # get data
            c = token.get_esi_client(spec_file=SWAGGER_SPEC_PATH)
            location = c.Location.get_characters_character_id_location(character_id=token.character_id).result()
            ship = c.Location.get_characters_character_id_ship(character_id=token.character_id).result()
            location['solar_system_name'] = \
                c.Universe.get_universe_systems_system_id(system_id=location['solar_system_id']).result()[
                    'name']
            if location['station_id']:
                location['station_name'] = \
                    c.Universe.get_universe_stations_station_id(station_id=location['station_id']).result()['name']
            elif location['structure_id']:
                location['station_name'] = \
                    c.Universe.get_universe_structures_structure_id(structure_id=location['structure_id']).result()[
                        'name']
            else:
                location['station_name'] = "No Station"
            ship['ship_type_name'] = provider.get_itemtype(ship['ship_type_id']).name

            fat = Fat()
            fat.system = location['solar_system_name']
            fat.station = location['station_name']
            fat.shiptype = ship['ship_type_name']
            fat.fatlink = fatlink
            fat.character = character
            fat.user = request.user
            try:
                fat.full_clean()
                fat.save()
                messages.success(request, _('Fleet participation registered.'))
            except ValidationError as e:
                err_messages = []
                for errorname, message in e.message_dict.items():
                    err_messages.append(message[0])
                messages.error(request, ' '.join(err_messages))
        else:
            context = {'character_id': token.character_id,
                       'character_name': token.character_name}
            return render(request, 'fleetactivitytracking/characternotexisting.html', context=context)
    else:
        messages.error(request, _('FAT link has expired.'))
    return redirect('fatlink:view')
예제 #3
0
def click_link(request: WSGIRequest, token, fatlink_hash: str = None):
    """
    click fatlink helper
    :param request:
    :param token:
    :param fatlink_hash:
    :return:
    """

    if fatlink_hash is None:
        request.session["msg"] = ["warning", "No FAT link hash provided."]

        return redirect("afat:dashboard")

    try:
        try:
            fleet = AFatLink.objects.get(hash=fatlink_hash)
        except AFatLink.DoesNotExist:
            request.session["msg"] = ["warning", "The hash provided is not valid."]

            return redirect("afat:dashboard")

        dur = ClickAFatDuration.objects.get(fleet=fleet)
        now = timezone.now() - timedelta(minutes=dur.duration)

        if now >= fleet.afattime:
            request.session["msg"] = [
                "warning",
                (
                    "Sorry, that FAT Link is expired. If you were on that fleet, "
                    "contact your FC about having your FAT manually added."
                ),
            ]

            return redirect("afat:dashboard")

        character = EveCharacter.objects.get(character_id=token.character_id)

        try:
            required_scopes = [
                "esi-location.read_location.v1",
                "esi-location.read_online.v1",
                "esi-location.read_ship_type.v1",
            ]
            esi_token = Token.get_token(token.character_id, required_scopes)

            # check if character is online
            character_online = esi.client.Location.get_characters_character_id_online(
                character_id=token.character_id, token=esi_token.valid_access_token()
            ).result()

            if character_online["online"] is True:
                # character location
                location = esi.client.Location.get_characters_character_id_location(
                    character_id=token.character_id,
                    token=esi_token.valid_access_token(),
                ).result()

                # current ship
                ship = esi.client.Location.get_characters_character_id_ship(
                    character_id=token.character_id,
                    token=esi_token.valid_access_token(),
                ).result()

                # system information
                system = esi.client.Universe.get_universe_systems_system_id(
                    system_id=location["solar_system_id"]
                ).result()["name"]

                ship_name = provider.get_itemtype(ship["ship_type_id"]).name

                try:
                    fat = AFat(
                        afatlink=fleet,
                        character=character,
                        system=system,
                        shiptype=ship_name,
                    )
                    fat.save()

                    if fleet.fleet is not None:
                        name = fleet.fleet
                    else:
                        name = fleet.hash

                    request.session["msg"] = [
                        "success",
                        (
                            "FAT registered for {character_name} "
                            "at {fleet_name}".format(
                                character_name=character.character_name, fleet_name=name
                            )
                        ),
                    ]

                    logger.info(
                        "Fleetparticipation for fleet {fleet_name} "
                        "registered for pilot {character_name}".format(
                            fleet_name=name, character_name=character.character_name
                        )
                    )

                    return redirect("afat:dashboard")
                except Exception:
                    request.session["msg"] = [
                        "warning",
                        (
                            "A FAT already exists for the selected character "
                            "({character_name}) and fleet combination.".format(
                                character_name=character.character_name
                            )
                        ),
                    ]

                    return redirect("afat:dashboard")
            else:
                request.session["msg"] = [
                    "warning",
                    (
                        "Cannot register the fleet participation for {character_name}. "
                        "The character needs to be online.".format(
                            character_name=character.character_name
                        )
                    ),
                ]

                return redirect("afat:dashboard")
        except Exception:
            request.session["msg"] = [
                "warning",
                (
                    "There was an issue with the token for {character_name}. "
                    "Please try again.".format(character_name=character.character_name)
                ),
            ]

            return redirect("afat:dashboard")
    except Exception:
        request.session["msg"] = [
            "warning",
            "The hash provided is not for a clickable FAT Link.",
        ]

        return redirect("afat:dashboard")
예제 #4
0
def srp_request_view(request, fleet_srp):
    logger.debug("srp_request_view called by user %s for fleet srp code %s" %
                 (request.user, fleet_srp))

    if SrpFleetMain.objects.filter(fleet_srp_code=fleet_srp).exists() is False:
        logger.error("Unable to locate SRP Fleet using code %s for user %s" %
                     (fleet_srp, request.user))
        messages.error(
            request,
            _('Unable to locate SRP code with ID %(srpfleetid)s') %
            {"srpfleetid": fleet_srp})
        return redirect("srp:management")

    if request.method == 'POST':
        form = SrpFleetUserRequestForm(request.POST)
        logger.debug("Request type POST contains form valid: %s" %
                     form.is_valid())

        if form.is_valid():
            if SrpUserRequest.objects.filter(
                    killboard_link=form.cleaned_data['killboard_link']).exists(
                    ):
                messages.error(
                    request, _("This Killboard link has already been posted."))
                return redirect("srp:management")

            character = request.user.profile.main_character
            srp_fleet_main = SrpFleetMain.objects.get(fleet_srp_code=fleet_srp)
            post_time = timezone.now()

            srp_request = SrpUserRequest()
            srp_request.killboard_link = form.cleaned_data['killboard_link']
            srp_request.additional_info = form.cleaned_data['additional_info']
            srp_request.character = character
            srp_request.srp_fleet_main = srp_fleet_main

            try:
                srp_kill_link = SRPManager.get_kill_id(
                    srp_request.killboard_link)
                (ship_type_id, ship_value,
                 victim_id) = SRPManager.get_kill_data(srp_kill_link)
            except ValueError:
                logger.debug(
                    "User %s Submitted Invalid Killmail Link %s or server could not be reached"
                    % (request.user, srp_request.killboard_link))
                # THIS SHOULD BE IN FORM VALIDATION
                messages.error(
                    request,
                    _("Your SRP request Killmail link is invalid. Please make sure you are using zKillboard."
                      ))
                return redirect("srp:management")

            if request.user.character_ownerships.filter(
                    character__character_id=str(victim_id)).exists():
                srp_request.srp_ship_name = provider.get_itemtype(
                    ship_type_id).name
                srp_request.kb_total_loss = ship_value
                srp_request.post_time = post_time
                srp_request.save()
                logger.info(
                    "Created SRP Request on behalf of user %s for fleet name %s"
                    % (request.user, srp_fleet_main.fleet_name))
                messages.success(
                    request,
                    _('Submitted SRP request for your %(ship)s.') %
                    {"ship": srp_request.srp_ship_name})
                return redirect("srp:management")
            else:
                messages.error(
                    request,
                    _("Character %(charid)s does not belong to your Auth account. Please add the API key for this character and try again"
                      ) % {"charid": victim_id})
            return redirect("srp:management")
    else:
        logger.debug("Returning blank SrpFleetUserRequestForm")
        form = SrpFleetUserRequestForm()

    render_items = {'form': form}

    return render(request, 'srp/request.html', context=render_items)
예제 #5
0
def add_fat(request: WSGIRequest,
            token,
            fatlink_hash: str = None) -> HttpResponseRedirect:
    """
    Click fat link helper
    :param request:
    :type request:
    :param token:
    :type token:
    :param fatlink_hash:
    :type fatlink_hash:
    :return:
    :rtype:
    """

    if fatlink_hash is None:
        messages.warning(
            request,
            mark_safe(_("<h4>Warning!</h4><p>No FAT link hash provided.</p>")),
        )

        return redirect("afat:dashboard")

    try:
        fleet = AFatLink.objects.get(hash=fatlink_hash, is_esilink=False)
    except AFatLink.DoesNotExist:
        messages.warning(
            request,
            mark_safe(
                _("<h4>Warning!</h4><p>The hash provided is not valid.</p>")),
        )

        return redirect("afat:dashboard")

    dur = ClickAFatDuration.objects.get(fleet=fleet)
    now = timezone.now() - timedelta(minutes=dur.duration)

    if now >= fleet.afattime:
        messages.warning(
            request,
            mark_safe(
                _("<h4>Warning!</h4>"
                  "<p>Sorry, that FAT Link is expired. "
                  "If you were on that fleet, contact your FC about "
                  "having your FAT manually added.</p>")),
        )

        return redirect("afat:dashboard")

    character = EveCharacter.objects.get(character_id=token.character_id)

    try:
        required_scopes = [
            "esi-location.read_location.v1",
            "esi-location.read_online.v1",
            "esi-location.read_ship_type.v1",
        ]
        esi_token = Token.get_token(token.character_id, required_scopes)
    except Exception:
        messages.warning(
            request,
            mark_safe(
                _(f"<h4>Warning!</h4><p>There was an issue with the ESI token for {character.character_name}. Please try again.</p>"
                  )),
        )

        return redirect("afat:dashboard")

    # Check if character is online
    character_online = esi.client.Location.get_characters_character_id_online(
        character_id=token.character_id,
        token=esi_token.valid_access_token()).result()

    if character_online["online"] is True:
        # Character location
        location = esi.client.Location.get_characters_character_id_location(
            character_id=token.character_id,
            token=esi_token.valid_access_token(),
        ).result()

        # Current ship
        ship = esi.client.Location.get_characters_character_id_ship(
            character_id=token.character_id,
            token=esi_token.valid_access_token(),
        ).result()

        # System information
        system = esi.client.Universe.get_universe_systems_system_id(
            system_id=location["solar_system_id"]).result()["name"]

        ship_name = provider.get_itemtype(ship["ship_type_id"]).name

        try:
            AFat(afatlink=fleet,
                 character=character,
                 system=system,
                 shiptype=ship_name).save()
        except IntegrityError:
            messages.warning(
                request,
                mark_safe(
                    _(f"<h4>Warning!</h4><p>A FAT already exists for the selected character ({character.character_name}) and fleet combination.</p>"
                      )),
            )
        else:
            if fleet.fleet is not None:
                fleet_name = fleet.fleet
            else:
                fleet_name = fleet.hash

            messages.success(
                request,
                mark_safe(
                    _(f"<h4>Success!</h4><p>FAT registered for {character.character_name} at {fleet_name}</p>"
                      )),
            )

            logger.info(
                f'Participation for fleet "{fleet_name}" registered for '
                f"pilot {character.character_name}")
    else:
        messages.warning(
            request,
            mark_safe(
                _(f"<h4>Warning!</h4><p>Cannot register the fleet participation for {character.character_name}. The character needs to be online.</p>"
                  )),
        )

    return redirect("afat:dashboard")
예제 #6
0
def srp_request_view(request, fleet_srp):
    logger.debug("srp_request_view called by user %s for fleet srp code %s" % (request.user, fleet_srp))

    if SrpFleetMain.objects.filter(fleet_srp_code=fleet_srp).exists() is False:
        logger.error("Unable to locate SRP Fleet using code %s for user %s" % (fleet_srp, request.user))
        messages.error(request,
                       _('Unable to locate SRP code with ID %(srpfleetid)s') % {"srpfleetid": fleet_srp})
        return redirect("srp:management")

    if request.method == 'POST':
        form = SrpFleetUserRequestForm(request.POST)
        logger.debug("Request type POST contains form valid: %s" % form.is_valid())

        if form.is_valid():
            if SrpUserRequest.objects.filter(killboard_link=form.cleaned_data['killboard_link']).exists():
                messages.error(request,
                               _("This Killboard link has already been posted."))
                return redirect("srp:management")

            character = request.user.profile.main_character
            srp_fleet_main = SrpFleetMain.objects.get(fleet_srp_code=fleet_srp)
            post_time = timezone.now()

            srp_request = SrpUserRequest()
            srp_request.killboard_link = form.cleaned_data['killboard_link']
            srp_request.additional_info = form.cleaned_data['additional_info']
            srp_request.character = character
            srp_request.srp_fleet_main = srp_fleet_main

            try:
                srp_kill_link = SRPManager.get_kill_id(srp_request.killboard_link)
                (ship_type_id, ship_value, victim_id) = SRPManager.get_kill_data(srp_kill_link)
            except ValueError:
                logger.debug("User %s Submitted Invalid Killmail Link %s or server could not be reached" % (
                    request.user, srp_request.killboard_link))
                # THIS SHOULD BE IN FORM VALIDATION
                messages.error(request,
                               _(
                                   "Your SRP request Killmail link is invalid. Please make sure you are using zKillboard."))
                return redirect("srp:management")

            if request.user.character_ownerships.filter(character__character_id=str(victim_id)).exists():
                srp_request.srp_ship_name = provider.get_itemtype(ship_type_id).name
                srp_request.kb_total_loss = ship_value
                srp_request.post_time = post_time
                srp_request.save()
                logger.info("Created SRP Request on behalf of user %s for fleet name %s" % (
                    request.user, srp_fleet_main.fleet_name))
                messages.success(request,
                                 _('Submitted SRP request for your %(ship)s.') % {"ship": srp_request.srp_ship_name})
                return redirect("srp:management")
            else:
                messages.error(request,
                               _(
                                   "Character %(charid)s does not belong to your Auth account. Please add the API key for this character and try again")
                               % {"charid": victim_id})
            return redirect("srp:management")
    else:
        logger.debug("Returning blank SrpFleetUserRequestForm")
        form = SrpFleetUserRequestForm()

    render_items = {'form': form}

    return render(request, 'srp/request.html', context=render_items)