def delete_fat(request: WSGIRequest, fatlink_hash: str, fat_id: int) -> HttpResponseRedirect: """ Delete fat helper :param request: :type request: :param fatlink_hash: :type fatlink_hash: :param fat_id: :type fat_id: :return: :rtype: """ try: link = AFatLink.objects.get(hash=fatlink_hash) except AFatLink.DoesNotExist: messages.error( request, mark_safe( _("<h4>Error!</h4>" "<p>The hash provided is either invalid or has been deleted.</p>" )), ) return redirect("afat:dashboard") try: fat_details = AFat.objects.get(pk=fat_id, afatlink_id=link.pk) except AFat.DoesNotExist: messages.error( request, mark_safe( _("<h4>Error!</h4><p>The hash and FAT ID do not match.</p>")), ) return redirect("afat:dashboard") fat_details.delete() write_log( request=request, log_event=AFatLog.Event.DELETE_FAT, log_text= f"The FAT for {fat_details.character.character_name} has been deleted", fatlink_hash=link.hash, ) messages.success( request, mark_safe( _(f'<h4>Success!</h4><p>The FAT for {fat_details.character.character_name} has been successfully deleted from FAT link "{fatlink_hash}".</p>' )), ) logger.info( f"The FAT for {fat_details.character.character_name} has " f'been deleted from FAT link "{fatlink_hash}" by {request.user}.') return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash)
def delete_fatlink(request: WSGIRequest, fatlink_hash: str = None) -> HttpResponseRedirect: """ Delete fat link helper :param request: :type request: :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: link = AFatLink.objects.get(hash=fatlink_hash) except AFatLink.DoesNotExist: messages.error( request, mark_safe( _("<h4>Error!</h4>" "<p>The fatlink hash provided is either invalid " "or the fatlink has already been deleted.</p>")), ) return redirect("afat:dashboard") AFat.objects.filter(afatlink_id=link.pk).delete() link.delete() write_log( request=request, log_event=AFatLog.Event.DELETE_FATLINK, log_text="FAT link deleted.", fatlink_hash=link.hash, ) messages.success( request, mark_safe( _(f'<h4>Success!</h4><p>The FAT Link "{fatlink_hash}" and all associated FATs have been successfully deleted.</p>' )), ) logger.info(f'Fat link "{fatlink_hash}" and all associated ' f"FATs have been deleted by {request.user}") return redirect("afat:fatlinks_overview")
def delete_fatlink(request: WSGIRequest, fatlink_hash: str = None) -> HttpResponseRedirect: """ delete fatlink helper :param request: :type request: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ if fatlink_hash is None: request.session["msg"] = ["warning", "No FAT Link hash provided."] return redirect("afat:dashboard") try: link = AFatLink.objects.get(hash=fatlink_hash) except AFatLink.DoesNotExist: request.session["msg"] = [ "danger", "The fatlink hash provided is either invalid or " "the fatlink has already been deleted.", ] return redirect("afat:dashboard") AFat.objects.filter(afatlink_id=link.pk).delete() link.delete() write_log( request=request, log_event=AFatLogEvent.DELETE_FATLINK, log_text="FAT link deleted.", fatlink_hash=link.hash, ) request.session["msg"] = [ "success", 'The FAT Link "{fatlink_hash}" and all associated FATs ' "have been successfully deleted.".format(fatlink_hash=fatlink_hash), ] logger.info( ('Fat link "{fatlink_hash}" and all associated ' "FATs have been deleted by {user}").format(fatlink_hash=fatlink_hash, user=request.user)) return redirect("afat:fatlinks_overview")
def test_helper_convert_logs_to_dict(self): # given self.client.force_login(self.user_with_manage_afat) request = self.factory.get(reverse("afat:dashboard")) request.user = self.user_with_manage_afat fatlink_hash = get_hash_on_save() fatlink_type_cta = AFatLinkType.objects.create(name="CTA") fatlink_created = AFatLink.objects.create( afattime=timezone.now(), fleet="April Fleet 1", creator=self.user_with_manage_afat, character=self.character_1001, hash=fatlink_hash, is_esilink=True, is_registered_on_esi=True, esi_fleet_id="3726458287", link_type=fatlink_type_cta, ) duration = ClickAFatDuration.objects.create(fleet=fatlink_created, duration=120) fleet_type = f" (Fleet Type: {fatlink_created.link_type.name})" write_log( request=request, log_event=AFatLog.Event.CREATE_FATLINK, log_text=( f'FAT link with name "{fatlink_created.fleet}"{fleet_type} and ' f"a duration of {duration.duration} minutes was created"), fatlink_hash=fatlink_created.hash, ) # when log = AFatLog.objects.get(fatlink_hash=fatlink_hash) log_time = log.log_time log_time_timestamp = log_time.timestamp() user_main_character = get_main_character_from_user(user=log.user) fatlink_link = reverse("afat:fatlinks_details_fatlink", args=[log.fatlink_hash]) fatlink_html = f'<a href="{fatlink_link}">{log.fatlink_hash}</a>' result = convert_logs_to_dict(log=log, fatlink_exists=True) # then self.assertDictEqual( result, { "log_time": { "time": log_time, "timestamp": log_time_timestamp }, "log_event": AFatLog.Event(log.log_event).label, "user": user_main_character, "fatlink": { "html": fatlink_html, "hash": log.fatlink_hash }, "description": log.log_text, }, )
def reopen_fatlink(request: WSGIRequest, fatlink_hash: str) -> HttpResponseRedirect: """ re-open fat link :param request: :type request: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ # if request.method == "POST": # fatlink_reopen_form = ExtendFatLinkDuration(request.POST) # # if fatlink_reopen_form.is_valid(): # duration = ClickAFatDuration.objects.get(fleet__hash=fatlink_hash) # reopen_for = fatlink_reopen_form.cleaned_data["duration"] # # # get minutes already passed since fatlink creation # created_at = duration.fleet.afattime # now = datetime.now() # # time_difference_in_minutes = get_time_delta(created_at, now, "minutes") # new_duration = ( # time_difference_in_minutes # + fatlink_reopen_form.cleaned_data["duration"] # ) # # duration.duration = new_duration # duration.save() try: fatlink_duration = ClickAFatDuration.objects.get( fleet__hash=fatlink_hash) if fatlink_duration.fleet.reopened is False: created_at = fatlink_duration.fleet.afattime now = datetime.now() time_difference_in_minutes = get_time_delta( created_at, now, "minutes") new_duration = (time_difference_in_minutes + AFAT_DEFAULT_FATLINK_REOPEN_DURATION) fatlink_duration.duration = new_duration fatlink_duration.save() fatlink_duration.fleet.reopened = True fatlink_duration.fleet.save() # writing DB log write_log( request=request, # log_event=AFatLogEvent.REOPEN_FATLINK, log_event=AFatLogEvent.REOPEN_FATLINK, log_text= (f"FAT link re-opened for a " f"duration of {AFAT_DEFAULT_FATLINK_REOPEN_DURATION} minutes" ), fatlink_hash=fatlink_duration.fleet.hash, ) logger.info(( f'FAT link with hash "{fatlink_hash}" ' f"re-opened by {request.user} for a " f"duration of {AFAT_DEFAULT_FATLINK_REOPEN_DURATION} minutes")) request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 5 else: request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 7 except ClickAFatDuration.DoesNotExist: request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 6 return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash)
def delete_fat(request: WSGIRequest, fatlink_hash: str, fat) -> HttpResponseRedirect: """ delete fat helper :param request: :type request: :param fatlink_hash: :type fatlink_hash: :param fat: :type fat: :return: :rtype: """ try: link = AFatLink.objects.get(hash=fatlink_hash) except AFatLink.DoesNotExist: request.session["msg"] = [ "danger", "The hash provided is either invalid or has been deleted.", ] return redirect("afat:dashboard") try: fat_details = AFat.objects.get(pk=fat, afatlink_id=link.pk) except AFat.DoesNotExist: request.session["msg"] = [ "danger", "The hash and FAT ID do not match.", ] return redirect("afat:dashboard") fat_details.delete() write_log( request=request, log_event=AFatLogEvent.DELETE_FAT, log_text="The FAT for {character_name} has been deleted".format( character_name=fat_details.character.character_name, ), fatlink_hash=link.hash, ) request.session["msg"] = [ "success", ("The FAT for {character_name} has been successfully " 'deleted from FAT link "{fatlink_hash}".').format( character_name=fat_details.character.character_name, fatlink_hash=fatlink_hash, ), ] logger.info(("The FAT for {character_name} has been deleted " 'from FAT link "{fatlink_hash}" by {user}.').format( character_name=fat_details.character.character_name, fatlink_hash=fatlink_hash, user=request.user, )) return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash)
def details_fatlink(request: WSGIRequest, fatlink_hash: str = None) -> HttpResponse: """ fatlink view :param request: :type request: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ if fatlink_hash is None: request.session["msg"] = ["warning", "No FAT Link hash provided."] return redirect("afat:dashboard") try: link = AFatLink.objects.get(hash=fatlink_hash) except AFatLink.DoesNotExist: request.session["msg"] = ["warning", "The hash provided is not valid."] return redirect("afat:dashboard") if request.method == "POST": fatlink_edit_form = FatLinkEditForm(request.POST) manual_fat_form = AFatManualFatForm(request.POST) if fatlink_edit_form.is_valid(): link.fleet = fatlink_edit_form.cleaned_data["fleet"] link.save() # writing DB log write_log( request=request, log_event=AFatLogEvent.CHANGE_FATLINK, log_text=( 'FAT link changed. Fleet name was set to "{fleet_name}"' ).format(fleet_name=link.fleet), fatlink_hash=link.hash, ) logger.info( ('FAT link with hash "{fatlink_hash}" changed. ' 'Fleet name was set to "{fleet_name}" by {user}').format( fatlink_hash=link.hash, fleet_name=link.fleet, user=request.user)) request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 1 elif manual_fat_form.is_valid(): character_name = manual_fat_form.cleaned_data["character"] system = manual_fat_form.cleaned_data["system"] shiptype = manual_fat_form.cleaned_data["shiptype"] character = get_or_create_character(name=character_name) if character is not None: AFat( afatlink_id=link.pk, character=character, system=system, shiptype=shiptype, ).save() request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 3 # writing DB log write_log( request=request, log_event=AFatLogEvent.MANUAL_FAT, log_text= ("Pilot {pilot_name} flying a {ship_type} was manually added" ).format( pilot_name=character.character_name, ship_type=shiptype, ), fatlink_hash=link.hash, ) logger.info(( "Pilot {pilot_name} flying a {ship_type} was manually added to " 'FAT link with hash "{fatlink_hash}" by {user}').format( fatlink_hash=link.hash, pilot_name=character.character_name, ship_type=shiptype, user=request.user, )) else: request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 4 else: request.session["{fatlink_hash}-task-code".format( fatlink_hash=fatlink_hash)] = 2 logger.info( 'FAT link "{fatlink_hash}" details view called by {user}'.format( fatlink_hash=fatlink_hash, user=request.user)) msg_code = None message = None if "msg" in request.session: msg_code = 0 message = request.session.pop("msg") elif ("{fatlink_hash}-creation-code".format(fatlink_hash=fatlink_hash) in request.session): msg_code = request.session.pop( "{fatlink_hash}-creation-code".format(fatlink_hash=fatlink_hash)) elif ("{fatlink_hash}-task-code".format(fatlink_hash=fatlink_hash) in request.session): msg_code = request.session.pop( "{fatlink_hash}-task-code".format(fatlink_hash=fatlink_hash)) # let's see if the link is still valid or has expired already and can be re-opened # and FATs can be manually added # (only possible for 24 hours after creating the FAT link) link_ongoing = True link_can_be_reopened = False link_expires = None manual_fat_can_be_added = False # time dependant settings try: dur = ClickAFatDuration.objects.get(fleet=link) link_expires = link.afattime + timedelta(minutes=dur.duration) now = timezone.now() if link_expires <= now: # link expired link_ongoing = False if (link.reopened is False and get_time_delta(link_expires, now, "minutes") < AFAT_DEFAULT_FATLINK_REOPEN_GRACE_TIME): link_can_be_reopened = True # manual fat still possible? # only possible if the FAT link has not been re-opened # and has been created within the last 24 hours if link.reopened is False and get_time_delta(link.afattime, now, "hours") < 24: manual_fat_can_be_added = True except ClickAFatDuration.DoesNotExist: # ESI link link_ongoing = False is_clickable_link = False if link.is_esilink is False: is_clickable_link = True context = { "msg_code": str(msg_code), "message": message, "link": link, "is_esi_link": link.is_esilink, "is_clickable_link": is_clickable_link, "link_expires": link_expires, "link_ongoing": link_ongoing, "link_can_be_reopened": link_can_be_reopened, "manual_fat_can_be_added": manual_fat_can_be_added, "reopen_grace_time": AFAT_DEFAULT_FATLINK_REOPEN_GRACE_TIME, "reopen_duration": AFAT_DEFAULT_FATLINK_REOPEN_DURATION, } return render(request, "afat/fatlinks_details_fatlink.html", context)
def create_esi_fatlink_callback(request: WSGIRequest, token, fatlink_hash: str) -> HttpResponseRedirect: """ helper: create ESI link (callback, used when coming back from character selection) :param request: :type request: :param token: :type token: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ # check if there is a fleet try: required_scopes = ["esi-fleets.read_fleet.v1"] esi_token = Token.get_token(token.character_id, required_scopes) fleet_from_esi = esi.client.Fleets.get_characters_character_id_fleet( character_id=token.character_id, token=esi_token.valid_access_token()).result() except Exception: # not in a fleet request.session["msg"] = [ "warning", "To use the ESI function, you neeed to be in fleet and you need to be " "the fleet boss! You can create a clickable FAT link and share it, " "if you like.", ] # return to "Add FAT Link" view return redirect("afat:fatlinks_add_fatlink") # check if this character already has a fleet creator_character = EveCharacter.objects.get( character_id=token.character_id) registered_fleets_for_creator = AFatLink.objects.filter( is_esilink=True, is_registered_on_esi=True, character__character_name=creator_character.character_name, ) fleet_already_registered = False character_has_registered_fleets = False registered_fleets_to_close = list() if registered_fleets_for_creator.count() > 0: character_has_registered_fleets = True for registered_fleet in registered_fleets_for_creator: if registered_fleet.esi_fleet_id == fleet_from_esi["fleet_id"]: # Character already has a fleet fleet_already_registered = True else: registered_fleets_to_close.append( {"registered_fleet": registered_fleet}) # if the FC already has a fleet and it is the same as already registered, # just throw a warning if fleet_already_registered is True: request.session["msg"] = [ "warning", "Fleet with ID {fleet_id} for your character {character_name} " "has already been registered and pilots joining this " "fleet are automatically tracked.".format( fleet_id=fleet_from_esi["fleet_id"], character_name=creator_character.character_name, ), ] # return to "Add FAT Link" view return redirect("afat:fatlinks_add_fatlink") # if it's a new fleet, remove all former registered fleets if there are any if (character_has_registered_fleets is True and fleet_already_registered is False and len(registered_fleets_to_close) > 0): for registered_fleet_to_close in registered_fleets_to_close: reason = (f"FC has opened a new fleet with the " f"character {creator_character.character_name}") logger.info( (f"Closing ESI FAT link with hash " f'"{registered_fleet_to_close["registered_fleet"].hash}". ' f"Reason: {reason}")) registered_fleet_to_close[ "registered_fleet"].is_registered_on_esi = False registered_fleet_to_close["registered_fleet"].save() # check if we deal with the fleet boss here try: esi_fleet_member = esi.client.Fleets.get_fleets_fleet_id_members( fleet_id=fleet_from_esi["fleet_id"], token=esi_token.valid_access_token(), ).result() except Exception: request.session["msg"] = [ "warning", "Not Fleet Boss! Only the fleet boss can utilize the ESI function. " "You can create a clickable FAT link and share it, if you like.", ] # return to "Add FAT Link" view return redirect("afat:fatlinks_add_fatlink") creator_character = EveCharacter.objects.get( character_id=token.character_id) # create the fatlink fatlink = AFatLink( afattime=timezone.now(), fleet=request.session["fatlink_form__name"], creator=request.user, character=creator_character, hash=fatlink_hash, is_esilink=True, is_registered_on_esi=True, esi_fleet_id=fleet_from_esi["fleet_id"], ) # add fleet type if there is any if request.session["fatlink_form__type"] is not None: fatlink.link_type_id = request.session["fatlink_form__type"] # save it fatlink.save() # writing DB log fleet_type = "" if fatlink.link_type: fleet_type = f" (Fleet Type: {fatlink.link_type.name})" write_log( request=request, log_event=AFatLogEvent.CREATE_FATLINK, log_text=( f'ESI FAT link with name "{request.session["fatlink_form__name"]}"' f"{fleet_type} was created by {request.user}"), fatlink_hash=fatlink.hash, ) logger.info((f'ESI FAT link "{fatlink_hash}" with name ' f'"{request.session["fatlink_form__name"]}"{fleet_type} ' f"was created by {request.user}")) # clear session del request.session["fatlink_form__name"] del request.session["fatlink_form__type"] # process fleet members in the background process_fats.delay(data_list=esi_fleet_member, data_source="esi", fatlink_hash=fatlink_hash) request.session["{fatlink_hash}-creation-code".format( fatlink_hash=fatlink_hash)] = 200 return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash)
def create_clickable_fatlink(request: WSGIRequest, ) -> HttpResponseRedirect: """ create clickable fat link :param request: :type request: :return: :rtype: """ if request.method == "POST": form = AFatClickFatForm(request.POST) if form.is_valid(): fatlink_hash = get_random_string(length=30) fatlink = AFatLink() fatlink.fleet = form.cleaned_data["name"] if form.cleaned_data["type"] is not None: fatlink.link_type = form.cleaned_data["type"] fatlink.creator = request.user fatlink.hash = fatlink_hash fatlink.afattime = timezone.now() fatlink.save() dur = ClickAFatDuration() dur.fleet = AFatLink.objects.get(hash=fatlink_hash) dur.duration = form.cleaned_data["duration"] dur.save() request.session["{fatlink_hash}-creation-code".format( fatlink_hash=fatlink_hash)] = 201 # writing DB log fleet_type = "" if fatlink.link_type: fleet_type = f" (Fleet Type: {fatlink.link_type.name})" write_log( request=request, log_event=AFatLogEvent.CREATE_FATLINK, log_text= (f'FAT link with name "{form.cleaned_data["name"]}"{fleet_type} and ' f'a duration of {form.cleaned_data["duration"]} minutes was created' ), fatlink_hash=fatlink.hash, ) logger.info( (f'FAT link "{fatlink_hash}" with name ' f'"{form.cleaned_data["name"]}"{fleet_type} and a duration ' f'of {form.cleaned_data["duration"]} minutes was created ' f"by {request.user}")) return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash) request.session["msg"] = [ "danger", "Something went wrong when attempting to submit yourclickable FAT Link.", ] return redirect("afat:dashboard") request.session["msg"] = [ "warning", ('You must fill out the form on the "Add FAT Link" ' "page to create a clickable FAT Link"), ] return redirect("afat:dashboard")
def reopen_fatlink(request: WSGIRequest, fatlink_hash: str) -> HttpResponseRedirect: """ Re-open fat link :param request: :type request: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ try: fatlink_duration = ClickAFatDuration.objects.get( fleet__hash=fatlink_hash) except ClickAFatDuration.DoesNotExist: messages.error( request, mark_safe( _("<h4>Error!</h4>" "<p>The hash you provided does not match with any FAT link.</p>" )), ) return redirect("afat:dashboard") if fatlink_duration.fleet.reopened is False: created_at = fatlink_duration.fleet.afattime now = datetime.now() time_difference_in_minutes = get_time_delta(created_at, now, "minutes") new_duration = time_difference_in_minutes + AFAT_DEFAULT_FATLINK_REOPEN_DURATION fatlink_duration.duration = new_duration fatlink_duration.save() fatlink_duration.fleet.reopened = True fatlink_duration.fleet.save() # writing DB log write_log( request=request, log_event=AFatLog.Event.REOPEN_FATLINK, log_text= (f"FAT link re-opened for a duration of {AFAT_DEFAULT_FATLINK_REOPEN_DURATION} minutes" ), fatlink_hash=fatlink_duration.fleet.hash, ) logger.info( f'FAT link with hash "{fatlink_hash}" ' f"re-opened by {request.user} for a " f"duration of {AFAT_DEFAULT_FATLINK_REOPEN_DURATION} minutes") messages.success( request, mark_safe( _("<h4>Success!</h4>" "<p>The FAT link has been successfully re-opened.</p>")), ) else: messages.warning( request, mark_safe( _("<h4>Warning!</h4>" "<p>This FAT link has already been re-opened. " "FAT links can be re-opened only once!</p>")), ) return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash)
def details_fatlink(request: WSGIRequest, fatlink_hash: str) -> HttpResponse: """ Fat link view :param request: :type request: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ try: link = AFatLink.objects.select_related_default().get(hash=fatlink_hash) except AFatLink.DoesNotExist: messages.warning( request, mark_safe( _("<h4>Warning!</h4><p>The hash provided is not valid.</p>")), ) return redirect("afat:dashboard") if request.method == "POST": fatlink_edit_form = FatLinkEditForm(request.POST) manual_fat_form = AFatManualFatForm(request.POST) if fatlink_edit_form.is_valid(): link.fleet = fatlink_edit_form.cleaned_data["fleet"] link.save() # Writing DB log write_log( request=request, log_event=AFatLog.Event.CHANGE_FATLINK, log_text= f'FAT link changed. Fleet name was set to "{link.fleet}"', fatlink_hash=link.hash, ) logger.info( f'FAT link with hash "{link.hash}" changed. ' f'Fleet name was set to "{link.fleet}" by {request.user}') messages.success( request, mark_safe( _("<h4>Success!</h4><p>Fleet name successfully changed.</p>" )), ) elif manual_fat_form.is_valid(): character_name = manual_fat_form.cleaned_data["character"] system = manual_fat_form.cleaned_data["system"] shiptype = manual_fat_form.cleaned_data["shiptype"] character = get_or_create_character(name=character_name) if character is not None: AFat( afatlink_id=link.pk, character=character, system=system, shiptype=shiptype, ).save() messages.success( request, mark_safe( _("<h4>Success!</h4><p>Manual FAT processed.</p>")), ) # Writing DB log write_log( request=request, log_event=AFatLog.Event.MANUAL_FAT, log_text=(f"Pilot {character.character_name} " f"flying a {shiptype} was manually added"), fatlink_hash=link.hash, ) logger.info( f"Pilot {character.character_name} flying a {shiptype} was" f" manually added to FAT link with " f'hash "{link.hash}" by {request.user}') else: messages.error( request, mark_safe( _("<h4>Oh No!</h4>" "<p>Manual FAT processing failed! " "The character name you entered was not found.</p>") ), ) else: messages.error( request, mark_safe(_("<h4>Oh No!</h4><p>Something went wrong!</p>")), ) logger.info( f'FAT link "{fatlink_hash}" details view called by {request.user}') # Let's see if the link is still valid or has expired already and can be re-opened # and FATs can be manually added # (only possible for 24 hours after creating the FAT link) link_ongoing = True link_can_be_reopened = False link_expires = None manual_fat_can_be_added = False # Time dependant settings try: dur = ClickAFatDuration.objects.get(fleet=link) except ClickAFatDuration.DoesNotExist: # ESI link link_ongoing = False else: link_expires = link.afattime + timedelta(minutes=dur.duration) now = timezone.now() if link_expires <= now: # Link expired link_ongoing = False if (link.reopened is False and get_time_delta(link_expires, now, "minutes") < AFAT_DEFAULT_FATLINK_REOPEN_GRACE_TIME): link_can_be_reopened = True # Manual fat still possible? # Only possible if the FAT link has not been re-opened # and has been created within the last 24 hours if link.reopened is False and get_time_delta(link.afattime, now, "hours") < 24: manual_fat_can_be_added = True is_clickable_link = False if link.is_esilink is False: is_clickable_link = True if link.is_esilink and link.is_registered_on_esi: link_ongoing = True context = { "link": link, "is_esi_link": link.is_esilink, "is_clickable_link": is_clickable_link, "link_expires": link_expires, "link_ongoing": link_ongoing, "link_can_be_reopened": link_can_be_reopened, "manual_fat_can_be_added": manual_fat_can_be_added, "reopen_grace_time": AFAT_DEFAULT_FATLINK_REOPEN_GRACE_TIME, "reopen_duration": AFAT_DEFAULT_FATLINK_REOPEN_DURATION, } return render(request, "afat/view/fatlinks/fatlinks_details_fatlink.html", context)
def create_esi_fatlink_callback(request: WSGIRequest, token, fatlink_hash: str) -> HttpResponseRedirect: """ Helper :: create ESI link (callback, used when coming back from character selection) :param request: :type request: :param token: :type token: :param fatlink_hash: :type fatlink_hash: :return: :rtype: """ # Check if there is a fleet try: required_scopes = ["esi-fleets.read_fleet.v1"] esi_token = Token.get_token(token.character_id, required_scopes) fleet_from_esi = esi.client.Fleets.get_characters_character_id_fleet( character_id=token.character_id, token=esi_token.valid_access_token()).result() except Exception: # Not in a fleet messages.warning( request, mark_safe( _("<h4>Warning!</h4>" "<p>To use the ESI function, you need to be in fleet and you need " "to be the fleet boss! You can create a clickable FAT link and " "share it, if you like.</p>")), ) # Return to "Add FAT Link" view return redirect("afat:fatlinks_add_fatlink") # check if this character already has a fleet creator_character = EveCharacter.objects.get( character_id=token.character_id) registered_fleets_for_creator = AFatLink.objects.select_related_default( ).filter( is_esilink=True, is_registered_on_esi=True, character__character_name=creator_character.character_name, ) fleet_already_registered = False character_has_registered_fleets = False registered_fleets_to_close = [] if registered_fleets_for_creator.count() > 0: character_has_registered_fleets = True for registered_fleet in registered_fleets_for_creator: if registered_fleet.esi_fleet_id == fleet_from_esi["fleet_id"]: # Character already has a fleet fleet_already_registered = True else: registered_fleets_to_close.append( {"registered_fleet": registered_fleet}) # If the FC already has a fleet, and it is the same as already registered, # just throw a warning if fleet_already_registered is True: messages.warning( request, mark_safe( _(f'<h4>Warning!</h4><p>Fleet with ID "{fleet_from_esi["fleet_id"]}" for your character {creator_character.character_name} has already been registered and pilots joining this fleet are automatically tracked.</p>' )), ) # Return to "Add FAT Link" view return redirect("afat:fatlinks_add_fatlink") # If it's a new fleet, remove all former registered fleets, if there are any if (character_has_registered_fleets is True and fleet_already_registered is False and len(registered_fleets_to_close) > 0): for registered_fleet_to_close in registered_fleets_to_close: reason = (f"FC has opened a new fleet with the " f"character {creator_character.character_name}") logger.info( f"Closing ESI FAT link with hash " f'"{registered_fleet_to_close["registered_fleet"].hash}". ' f"Reason: {reason}") registered_fleet_to_close[ "registered_fleet"].is_registered_on_esi = False registered_fleet_to_close["registered_fleet"].save() # Check if we deal with the fleet boss here try: esi_fleet_member = esi.client.Fleets.get_fleets_fleet_id_members( fleet_id=fleet_from_esi["fleet_id"], token=esi_token.valid_access_token(), ).result() except Exception: messages.warning( request, mark_safe( _("<h4>Warning!</h4>" "<p>Not Fleet Boss! Only the fleet boss can utilize the ESI " "function. You can create a clickable FAT link and share it, " "if you like.</p>")), ) # Return to "Add FAT Link" view return redirect("afat:fatlinks_add_fatlink") creator_character = EveCharacter.objects.get( character_id=token.character_id) # Create the fat link fatlink = AFatLink( afattime=timezone.now(), fleet=request.session["fatlink_form__name"], creator=request.user, character=creator_character, hash=fatlink_hash, is_esilink=True, is_registered_on_esi=True, esi_fleet_id=fleet_from_esi["fleet_id"], ) # Add fleet type, if there is any if request.session["fatlink_form__type"] is not None: fatlink.link_type_id = request.session["fatlink_form__type"] # Save it fatlink.save() # Writing DB log fleet_type = "" if fatlink.link_type: fleet_type = f"(Fleet Type: {fatlink.link_type.name})" write_log( request=request, log_event=AFatLog.Event.CREATE_FATLINK, log_text=( f'ESI FAT link with name "{request.session["fatlink_form__name"]}" ' f"{fleet_type} was created by {request.user}"), fatlink_hash=fatlink.hash, ) logger.info(f'ESI FAT link "{fatlink_hash}" with name ' f'"{request.session["fatlink_form__name"]}"{fleet_type} ' f"was created by {request.user}") # Clear session del request.session["fatlink_form__name"] del request.session["fatlink_form__type"] # Process fleet members in background process_fats.delay(data_list=esi_fleet_member, data_source="esi", fatlink_hash=fatlink_hash) messages.success( request, mark_safe( _("<h4>Success!</h4>" "<p>FAT Link Created!</p>" "<p>FATs have been queued, they may take a few mins to show up.</p>" "<p>Pilots who join later will be automatically added until you " "close or leave the fleet in-game.</p>")), ) return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash)
def create_clickable_fatlink(request: WSGIRequest, ) -> HttpResponseRedirect: """ Create clickable fat link :param request: :type request: :return: :rtype: """ if request.method == "POST": form = AFatClickFatForm(request.POST) if form.is_valid(): fatlink_hash = get_hash_on_save() fatlink = AFatLink() fatlink.fleet = form.cleaned_data["name"] if form.cleaned_data["type"] is not None: fatlink.link_type = form.cleaned_data["type"] fatlink.creator = request.user fatlink.hash = fatlink_hash fatlink.afattime = timezone.now() fatlink.save() dur = ClickAFatDuration() dur.fleet = AFatLink.objects.get(hash=fatlink_hash) dur.duration = form.cleaned_data["duration"] dur.save() # Writing DB log fleet_type = (f" (Fleet Type: {fatlink.link_type.name})" if fatlink.link_type else "") write_log( request=request, log_event=AFatLog.Event.CREATE_FATLINK, log_text= (f'FAT link with name "{form.cleaned_data["name"]}"{fleet_type} and ' f'a duration of {form.cleaned_data["duration"]} minutes was created' ), fatlink_hash=fatlink.hash, ) logger.info( f'FAT link "{fatlink_hash}" with name ' f'"{form.cleaned_data["name"]}"{fleet_type} and a duration ' f'of {form.cleaned_data["duration"]} minutes was created ' f"by {request.user}") messages.success( request, mark_safe( _("<h4>Success!</h4>" "<p>Clickable FAT Link Created!</p>" "<p>Make sure to give your fleet members the link to " "click so that they get credit for this fleet.</p>")), ) return redirect("afat:fatlinks_details_fatlink", fatlink_hash=fatlink_hash) messages.error( request, mark_safe( _("<h4>Error!</h4>" "<p>Something went wrong when attempting " "to submit your clickable FAT Link.</p>")), ) return redirect("afat:fatlinks_add_fatlink") messages.warning( request, mark_safe( _("<h4>Warning!</h4>" '<p>You must fill out the form on the "Add FAT Link" ' "page to create a clickable FAT Link</p>")), ) return redirect("afat:fatlinks_add_fatlink")
user = User.objects.first() creator = user.profile.main_character link_type, _ = AFatLinkType.objects.get_or_create(name="Generated Fleet") for _ in range(LINKS_NUMBER): fat_link = AFatLink.objects.create( fleet=f"Generated Fleet #{random.randint(1, 1000000000)}", hash=random_string(20), creator=user, character=creator, link_type=link_type, afattime=now() - dt.timedelta(days=random.randint(0, 180)), ) write_log( request=RequestStub(user), log_event=AFatLog.Event.CREATE_FATLINK, log_text=(f'ESI FAT link with name "{fat_link.fleet}"' f"{link_type} was created by {user}"), fatlink_hash=fat_link.hash, ) for character in random.sample(characters, k=random.randint(1, len(characters))): AFat.objects.create( character_id=character.id, afatlink=fat_link, system="Jita", shiptype="Ibis", ) print(".", end="", flush=True) print("") print("DONE")