Exemplo n.º 1
0
    def clean(self):
        if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
            raise forms.ValidationError(u'API key already exist')

        check_blue = False
        try:
            check_blue = self.cleaned_data['is_blue']
        except:
            pass

        if check_blue:
            if settings.BLUE_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(self.cleaned_data['api_id'],
                                                               self.cleaned_data['api_key']):
                    raise forms.ValidationError(u'API not of type account')

            if not EveApiManager.check_blue_api_is_full(self.cleaned_data['api_id'],
                                                   self.cleaned_data['api_key']):
                raise forms.ValidationError(u'API supplied is too restricted. Minimum access mask is ' + str(settings.BLUE_API_MASK))

        else:
            if settings.MEMBER_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(self.cleaned_data['api_id'],
                                                           self.cleaned_data['api_key']):
                    raise forms.ValidationError(u'API not of type account')

            if not EveApiManager.check_api_is_full(self.cleaned_data['api_id'],
                                                   self.cleaned_data['api_key']):
                raise forms.ValidationError(u'API supplied is too restricted. Minimum access mask is ' + str(settings.MEMBER_API_MASK))

        return self.cleaned_data
Exemplo n.º 2
0
    def clean(self):
        super(UpdateKeyForm, self).clean()

        if 'api_id' in self.cleaned_data and 'api_key' in self.cleaned_data:
            if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
                logger.debug("UpdateKeyForm failed cleaning as API id %s already exists." % self.cleaned_data['api_id'])
                raise forms.ValidationError(u'API key already exist')
            if EveApiManager.api_key_is_valid(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                raise forms.ValidationError(u'API key is invalid')
            chars = EveApiManager.get_characters_from_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']).result
            states = []
            states.append(self.user_state)
            for char in chars:
                evechar = EveCharacter()
                evechar.character_name = chars[char]['name']
                evechar.corporation_id = chars[char]['corp']['id']
                evechar.alliance_id = chars[char]['alliance']['id']
                state = determine_membership_by_character(evechar)
                logger.debug("API ID %s character %s has state %s" % (self.cleaned_data['api_id'], evechar, state))
                states.append(state)

            if 'MEMBER' in states:
                if EveApiManager.validate_member_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                    raise forms.ValidationError(u'API must meet member requirements')
            if 'BLUE' in states:
                if EveApiManager.validate_blue_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                    raise forms.ValidationError(u'API must meet blue requirements')
        return self.cleaned_data
Exemplo n.º 3
0
def populate_alliance(id, blue=False):
    logger.debug("Populating alliance model with id %s blue %s" % (id, blue))
    alliance_info = EveApiManager.get_alliance_information(id)

    if not alliance_info:
        raise ValueError("Supplied alliance id %s is invalid" % id)

    if not EveAllianceInfo.objects.filter(alliance_id=id).exists():
        EveManager.create_alliance_info(alliance_info['id'],
                                        alliance_info['name'],
                                        alliance_info['ticker'],
                                        alliance_info['executor_id'],
                                        alliance_info['member_count'], blue)
    alliance = EveAllianceInfo.objects.get(alliance_id=id)
    for member_corp in alliance_info['member_corps']:
        if EveCorporationInfo.objects.filter(
                corporation_id=member_corp).exists():
            corp = EveCorporationInfo.objects.get(corporation_id=member_corp)
            if corp.alliance != alliance:
                corp.alliance = alliance
                corp.save()
        else:
            logger.info("Creating new alliance member corp id %s" %
                        member_corp)
            corpinfo = EveApiManager.get_corporation_information(member_corp)
            EveManager.create_corporation_info(corpinfo['id'],
                                               corpinfo['name'],
                                               corpinfo['ticker'],
                                               corpinfo['members']['current'],
                                               blue, alliance)
Exemplo n.º 4
0
def run_alliance_corp_update():
    # I am not proud of this block of code
    if EveApiManager.check_if_api_server_online():
        # Get Corp info
        corp_info = EveApiManager.get_corporation_information(settings.ALLIANCE_ID, settings.ALLIANCE_EXEC_CORP_ID,
                                                              settings.ALLIANCE_EXEC_CORP_VCODE)

        # Dummy alliance info
        if not EveManager.check_if_alliance_exists_by_id(settings.ALLIANCE_ID):
            EveManager.create_alliance_info(settings.ALLIANCE_ID, corp_info['name'], corp_info['ticker'],
                                            settings.ALLIANCE_ID, 1, False)
        else:
            # Update semi fake data no real point
            EveManager.update_alliance_info(settings.ALLIANCE_ID, settings.ALLIANCE_ID,
                                            1, False)

        # Get the fake data we just added / updated
        alliance = EveManager.get_alliance_info_by_id(settings.ALLIANCE_ID)

        # Only one corp add or update
        if not EveManager.check_if_corporation_exists_by_id(corp_info['id']):
            EveManager.create_corporation_info(corp_info['id'], corp_info['name'], corp_info['ticker'],
                                               corp_info['members']['current'], False, alliance)
        else:
            EveManager.update_corporation_info(corp_info['id'], corp_info['members']['current'], alliance,
                                               False)
Exemplo n.º 5
0
    def clean(self):
        super(UpdateKeyForm, self).clean()

        if 'api_id' in self.cleaned_data and 'api_key' in self.cleaned_data:
            try:
                if EveManager.check_if_api_key_pair_exist(
                        self.cleaned_data['api_id']):
                    logger.debug(
                        "UpdateKeyForm failed cleaning as API id %s already exists."
                        % self.cleaned_data['api_id'])
                    raise forms.ValidationError(u'API key already exist')
                if EveApiManager.api_key_is_valid(
                        self.cleaned_data['api_id'],
                        self.cleaned_data['api_key']) is False:
                    raise forms.ValidationError(u'API key is invalid')
                if (settings.REJECT_OLD_APIS
                        and EveManager.check_if_api_key_pair_is_new(
                            self.cleaned_data['api_id'],
                            settings.REJECT_OLD_APIS_MARGIN) is False):
                    raise forms.ValidationError(
                        u'API key is too old. Please create a new key')
                chars = EveApiManager.get_characters_from_api(
                    self.cleaned_data['api_id'],
                    self.cleaned_data['api_key']).result
                states = []
                states.append(self.user_state)
                for char in chars:
                    evechar = EveCharacter()
                    evechar.character_name = chars[char]['name']
                    evechar.corporation_id = chars[char]['corp']['id']
                    evechar.alliance_id = chars[char]['alliance']['id']
                    state = determine_membership_by_character(evechar)
                    logger.debug("API ID %s character %s has state %s" %
                                 (self.cleaned_data['api_id'], evechar, state))
                    states.append(state)

                if 'MEMBER' in states:
                    if EveApiManager.validate_member_api(
                            self.cleaned_data['api_id'],
                            self.cleaned_data['api_key']) is False:
                        raise forms.ValidationError(
                            u'API must meet member requirements')
                if 'BLUE' in states:
                    if EveApiManager.validate_blue_api(
                            self.cleaned_data['api_id'],
                            self.cleaned_data['api_key']) is False:
                        raise forms.ValidationError(
                            u'API must meet blue requirements')
                return self.cleaned_data
            except evelink.api.APIError as e:
                logger.debug("Got error code %s while validating API %s" %
                             (e.code, self.cleaned_data['api_id']))
                if int(e.code) in [221, 222]:
                    raise forms.ValidationError("API key failed validation")
                else:
                    raise forms.ValidationError("Failed to reach API servers")
Exemplo n.º 6
0
def run_api_refresh():

    users = User.objects.all()

    for user in users:
        # Check if the api server is online
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            if api_key_pairs:
                authserviceinfo = AuthServicesInfo.objects.get(user=user)

                if settings.DEBUG:
                    print 'Running update on user: '******'Running on ' + api_key_pair.api_id + ':' + api_key_pair.api_key
                        if EveApiManager.api_key_is_valid(api_key_pair.api_id, api_key_pair.api_key):
                            # Update characters
                            characters = EveApiManager.get_characters_from_api(api_key_pair.api_id,
                                                                               api_key_pair.api_key)
                            EveManager.update_characters_from_list(characters)
                            # Check our main character
                            character = EveManager.get_character_by_id(authserviceinfo.main_char_id)
                            main_alliance_id = EveManager.get_charater_corporation_id_by_id(
                                authserviceinfo.main_char_id)

                            # NPC corps return as None
                            if main_alliance_id is None or int(main_alliance_id) != int(settings.ALLIANCE_ID):
                                if settings.DEBUG:
                                    print 'Not in Corp'

                                SlackManager.send_director('API ERROR: ' + user.username +
                                                           ' Not in corp.\n\tServices disabled.\n\tAPI removed.')

                                remove_user_all_groups(user)
                                deactivate_services(user)
                                EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
                                EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
                        else:
                            if settings.DEBUG:
                                print 'Bad API Deleting character and api for ' + user.username

                            SlackManager.send_director('API ERROR: Bad API for user ' + user.username +
                                                       '\n\tServices disabled.\n\tAPI removed.')

                            remove_user_all_groups(user)
                            deactivate_services(user)
                            EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
                            EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)

                else:
                    if settings.DEBUG:
                        print 'No main_char_id set'
Exemplo n.º 7
0
def update_corp(id):
    corp = EveCorporationInfo.objects.get(corporation_id=id)
    logger.debug("Updating corp %s" % corp)
    corpinfo = EveApiManager.get_corporation_information(corp.corporation_id)
    if corpinfo:
        alliance = None
        if EveAllianceInfo.objects.filter(alliance_id=corpinfo['alliance']['id']).exists():
            alliance = EveAllianceInfo.objects.get(alliance_id=corpinfo['alliance']['id'])
        EveManager.update_corporation_info(corpinfo['id'], corpinfo['members']['current'], alliance, corp.is_blue)
    elif EveApiManager.check_if_corp_exists(corp.corporation_id) is False:
        logger.info("Corp %s has closed. Deleting model" % corp)
        corp.delete()    
Exemplo n.º 8
0
def update_corp(id):
    corp = EveCorporationInfo.objects.get(corporation_id=id)
    logger.debug("Updating corp %s" % corp)
    corpinfo = EveApiManager.get_corporation_information(corp.corporation_id)
    if corpinfo:
        alliance = None
        if EveAllianceInfo.objects.filter(alliance_id=corpinfo['alliance']['id']).exists():
            alliance = EveAllianceInfo.objects.get(alliance_id=corpinfo['alliance']['id'])
        EveManager.update_corporation_info(corpinfo['id'], corpinfo['members']['current'], alliance, corp.is_blue)
    elif EveApiManager.check_if_corp_exists(corp.corporation_id) is False:
        logger.info("Corp %s has closed. Deleting model" % corp)
        corp.delete()    
Exemplo n.º 9
0
def refresh_api(api):
    logger.debug('Running update on api key %s' % api.api_id)
    still_valid = True
    try:
        EveApiManager.validate_api(api.api_id, api.api_key, api.user)
        # Update characters
        characters = EveApiManager.get_characters_from_api(api.api_id, api.api_key)
        EveManager.update_characters_from_list(characters)
        new_character = False
        for char in characters.result:
            # Ensure we have a model for all characters on key
            if not EveManager.check_if_character_exist(characters.result[char]['name']):
                logger.debug(
                    "API key %s has a new character on the account: %s" % (api.api_id, characters.result[char]['name']))
                new_character = True
        if new_character:
            logger.debug("Creating new character %s from api key %s" % (characters.result[char]['name'], api.api_id))
            EveManager.create_characters_from_list(characters, api.user, api.api_id)
        current_chars = EveCharacter.objects.filter(api_id=api.api_id)
        for c in current_chars:
            if not int(c.character_id) in characters.result:
                logger.info("Character %s no longer found on API ID %s" % (c, api.api_id))
                c.delete()
    except evelink.api.APIError as e:
        logger.warning('Received unexpected APIError (%s) while updating API %s' % (e.code, api.api_id))
    except EveApiManager.ApiInvalidError:
        logger.debug("API key %s is no longer valid; it and its characters will be deleted." % api.api_id)
        notify(api.user, "API Failed Validation", message="Your API key ID %s is no longer valid." % api.api_id,
               level="danger")
        still_valid = False
    except EveApiManager.ApiAccountValidationError:
        logger.info(
            "Determined api key %s for user %s no longer meets account access requirements." % (api.api_id, api.user))
        notify(api.user, "API Failed Validation",
               message="Your API key ID %s is no longer account-wide as required." % api.api_id, level="danger")
        still_valid = False
    except EveApiManager.ApiMaskValidationError as e:
        logger.info("Determined api key %s for user %s no longer meets minimum access mask as required." % (
            api.api_id, api.user))
        notify(api.user, "API Failed Validation",
               message="Your API key ID %s no longer meets access mask requirements. Required: %s Got: %s" % (
                   api.api_id, e.required_mask, e.api_mask), level="danger")
        still_valid = False
    except EveApiManager.ApiServerUnreachableError as e:
        logger.warn("Error updating API %s\n%s" % (api.api_id, str(e)))
    finally:
        if not still_valid:
            EveManager.delete_characters_by_api_id(api.api_id, api.user.id)
            EveManager.delete_api_key_pair(api.api_id, api.user.id)
            notify(api.user, "API Key Deleted",
                   message="Your API key ID %s is invalid. It and its associated characters have been deleted." % api.api_id,
                   level="danger")
Exemplo n.º 10
0
def run_api_refresh():
    users = User.objects.all()

    for user in users:
        # Check if the api server is online
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            if api_key_pairs:
                valid_key = False
                authserviceinfo = AuthServicesInfo.objects.get(user=user)

                print 'Running update on user: '******'Running on ' + api_key_pair.api_id + ':' + api_key_pair.api_key
                            if EveApiManager.api_key_is_valid(
                                    api_key_pair.api_id, api_key_pair.api_key):
                                # Update characters
                                characters = EveApiManager.get_characters_from_api(
                                    api_key_pair.api_id, api_key_pair.api_key)
                                EveManager.update_characters_from_list(
                                    characters)
                                valid_key = True
                            else:
                                EveManager.delete_characters_by_api_id(
                                    api_key_pair.api_id, user)
                                EveManager.delete_api_key_pair(
                                    api_key_pair.api_id, api_key_pair.api_key)

                        if valid_key:
                            # Check our main character
                            character = EveManager.get_character_by_id(
                                authserviceinfo.main_char_id)
                            corp = EveManager.get_corporation_info_by_id(
                                character.corporation_id)
                            main_alliance_id = EveManager.get_charater_alliance_id_by_id(
                                authserviceinfo.main_char_id)
                            if main_alliance_id == settings.ALLIANCE_ID:
                                pass
                            elif corp is not None:
                                if corp.is_blue is not True:
                                    deactivate_services(user)
                            else:
                                deactivate_services(user)
                        else:
                            # nuke it
                            deactivate_services(user)
                else:
                    print 'No main_char_id set'
Exemplo n.º 11
0
def api_sso_validate(request, tokens, api_id):
    logger.debug('api_sso_validate called by user %s for api %s' % (request.user, api_id))
    api = get_object_or_404(EveApiKeyPair, api_id=api_id)
    if api.user and api.user != request.user:
        logger.warning('User %s attempting to take ownership of api %s from %s' % (request.user, api_id, api.user))
        messages.warning(request, 'API %s already claimed by user %s' % (api_id, api.user))
        return redirect('auth_api_key_management')
    elif api.sso_verified:
        logger.debug('API %s has already been verified.' % api_id)
        messages.info(request, 'API %s has already been verified' % api_id)
        return redirect('auth_api_key_management')
    token = tokens[0]
    logger.debug('API %s has not been verified. Checking if token for %s matches.' % (api_id, token.character_name))
    characters = EveApiManager.get_characters_from_api(api.api_id, api.api_key).result
    if token.character_id in characters:
        api.user = request.user
        api.sso_verified = True
        api.save()
        EveCharacter.objects.filter(character_id__in=characters).update(user=request.user, api_id=api_id)
        messages.success(request, 'Confirmed ownership of API %s' % api.api_id)
        auth, c = AuthServicesInfo.objects.get_or_create(user=request.user)
        if not auth.main_char_id:
            return redirect('auth_characters')
        return redirect('auth_api_key_management')
    else:
        messages.warning(request, '%s not found on API %s. Please SSO as a character on the API.' % (token.character_name, api.api_id))
    return render(request, 'registered/apisso.html', context={'api':api})
Exemplo n.º 12
0
def run_api_refresh():
    users = User.objects.all()
    logger.debug("Running api refresh on %s users." % len(users))
    for user in users:
        # Check if the api server is online
        logger.debug("Running api refresh for user %s" % user)
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            logger.debug("User %s has api key pairs %s" % (user, api_key_pairs))
            if api_key_pairs:
                authserviceinfo, c = AuthServicesInfo.objects.get_or_create(user=user)
                logger.debug("User %s has api keys. Proceeding to refresh." % user)
                for api_key_pair in api_key_pairs:
                    try:
                        refresh_api(api_key_pair)
                    except evelink.api.APIError as e:
                        if int(e.code) >= 500:
                            logger.error("EVE API servers encountered error %s updating %s" % (e.code, api_key_pair))
                        elif int(e.code) == 221:
                            logger.warn("API server hiccup %s while updating %s" % (e.code, api_key_pair))
                        else:
                            logger.info("API key %s failed update with error code %s" % (api_key_pair.api_id, e.code))
                            EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
                            EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
                            notify(user, "API Key Deleted", message="Your API key ID %s failed validation with code %s. It and its associated characters have been deleted." % (api_key_pair.api_id, e.code), level="danger")
                # Check our main character
                if EveCharacter.objects.filter(character_id=authserviceinfo.main_char_id).exists() is False:
                    logger.info("User %s main character id %s missing model. Clearning main character." % (user, authserviceinfo.main_char_id))
                    authserviceinfo.main_char_id = ''
                    authserviceinfo.save()
                    notify(user, "Main Character Reset", message="Your specified main character no longer has a model.\nThis could be the result of an invalid API\nYour main character ID has been reset.", level="warn")
        set_state(user)
Exemplo n.º 13
0
def add_api_key(request):
    logger.debug("add_api_key called by user %s" % request.user)
    user_state = determine_membership_by_user(request.user)
    if request.method == "POST":
        form = UpdateKeyForm(request.POST)
        form.user_state = user_state
        logger.debug("Request type POST with form valid: %s" % form.is_valid())
        if form.is_valid():
            EveManager.create_api_keypair(form.cleaned_data["api_id"], form.cleaned_data["api_key"], request.user)

            # Grab characters associated with the key pair
            characters = EveApiManager.get_characters_from_api(
                form.cleaned_data["api_id"], form.cleaned_data["api_key"]
            )
            EveManager.create_characters_from_list(characters, request.user, form.cleaned_data["api_id"])
            logger.info("Successfully processed api add form for user %s" % request.user)
            return HttpResponseRedirect("/api_key_management/")
        else:
            logger.debug("Form invalid: returning to form.")
    else:
        logger.debug("Providing empty update key form for user %s" % request.user)
        form = UpdateKeyForm()
        form.user_state = user_state
    context = {"form": form, "apikeypairs": EveManager.get_api_key_pairs(request.user.id)}
    return render_to_response("registered/addapikey.html", context, context_instance=RequestContext(request))
Exemplo n.º 14
0
def run_api_refresh():
    if not EveApiManager.check_if_api_server_online():
        logger.warn("Aborted scheduled API key refresh: API server unreachable")
        return

    for u in User.objects.all():
        refresh_user_apis.delay(u.pk)
Exemplo n.º 15
0
def api_sso_validate(request, tokens, api_id):
    logger.debug('api_sso_validate called by user %s for api %s' %
                 (request.user, api_id))
    api = get_object_or_404(EveApiKeyPair, api_id=api_id)
    if api.user:
        logger.warning(
            'User %s attempting to take ownership of api %s from %s' %
            (request.user, api_id, api.user))
        messages.warning(
            request, 'API %s already claimed by user %s' % (api_id, api.user))
        return redirect('auth_api_key_management')
    token = tokens[0]
    logger.debug('API %s has no owner. Checking if token for %s matches.' %
                 (api_id, token.character_name))
    characters = EveApiManager.get_characters_from_api(api.api_id,
                                                       api.api_key).result
    if token.character_id in characters:
        api.user = request.user
        api.save()
        EveCharacter.objects.filter(character_id__in=characters).update(
            user=request.user, api_id=api_id)
        messages.success(request, 'Confirmed ownership of API %s' % api.api_id)
        auth, c = AuthServicesInfo.objects.get_or_create(user=request.user)
        if not auth.main_char_id:
            return redirect('auth_characters')
        return redirect('auth_api_key_management')
    else:
        messages.warning(
            request,
            '%s not found on API %s. Please SSO as a character on the API.' %
            (token.character_name, api.api_id))
    return render(request, 'registered/apisso.html', context={'api': api})
Exemplo n.º 16
0
def run_api_refresh():
    users = User.objects.all()
    logger.debug("Running api refresh on %s users." % len(users))
    for user in users:
        # Check if the api server is online
        logger.debug("Running api refresh for user %s" % user)
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            logger.debug("User %s has api key pairs %s" % (user, api_key_pairs))
            if api_key_pairs:
                authserviceinfo, c = AuthServicesInfo.objects.get_or_create(user=user)
                logger.debug("User %s has api keys. Proceeding to refresh." % user)
                for api_key_pair in api_key_pairs:
                    try:
                        refresh_api(api_key_pair)
                    except evelink.api.APIError as e:
                        if int(e.code) >= 500:
                            logger.error("EVE API servers encountered error %s updating %s" % (e.code, api_key_pair))
                        elif int(e.code) == 221:
                            logger.warn("API server hiccup %s while updating %s" % (e.code, api_key_pair))
                        else:
                            logger.info("API key %s failed update with error code %s" % (api_key_pair.api_id, e.code))
                            EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
                            EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
                            notify(user, "API Key Deleted", message="Your API key ID %s failed validation with code %s. It and its associated characters have been deleted." % (api_key_pair.api_id, e.code), level="danger")
                # Check our main character
                if EveCharacter.objects.filter(character_id=authserviceinfo.main_char_id).exists() is False:
                    logger.info("User %s main character id %s missing model. Clearning main character." % (user, authserviceinfo.main_char_id))
                    authserviceinfo.main_char_id = ''
                    authserviceinfo.save()
                    notify(user, "Main Character Reset", message="Your specified main character no longer has a model.\nThis could be the result of an invalid API\nYour main character ID has been reset.", level="warn")
        set_state(user)
Exemplo n.º 17
0
def add_api_key(request):
    logger.debug("add_api_key called by user %s" % request.user)
    user_state = determine_membership_by_user(request.user)
    if request.method == 'POST':
        form = UpdateKeyForm(request.POST)
        form.user_state = user_state
        logger.debug("Request type POST with form valid: %s" % form.is_valid())
        if form.is_valid():
            EveManager.create_api_keypair(form.cleaned_data['api_id'],
                                          form.cleaned_data['api_key'],
                                          request.user)

            # Grab characters associated with the key pair
            characters = EveApiManager.get_characters_from_api(
                form.cleaned_data['api_id'], form.cleaned_data['api_key'])
            EveManager.create_characters_from_list(characters, request.user,
                                                   form.cleaned_data['api_id'])
            logger.info("Successfully processed api add form for user %s" %
                        request.user)
            return HttpResponseRedirect("/api_key_management/")
        else:
            logger.debug("Form invalid: returning to form.")
    else:
        logger.debug("Providing empty update key form for user %s" %
                     request.user)
        form = UpdateKeyForm()
        form.user_state = user_state
    context = {
        'form': form,
        'apikeypairs': EveManager.get_api_key_pairs(request.user.id)
    }
    return render_to_response('registered/addapikey.html',
                              context,
                              context_instance=RequestContext(request))
Exemplo n.º 18
0
def run_api_refresh():
    if not EveApiManager.check_if_api_server_online():
        logger.warn("Aborted scheduled API key refresh: API server unreachable")
        return

    for u in User.objects.all():
        refresh_user_apis.delay(u)
Exemplo n.º 19
0
def refresh_api(api):
    logger.debug('Running update on api key %s' % api.api_id)
    still_valid = True
    try:
        EveApiManager.validate_api(api.api_id, api.api_key, api.user)
        # Update characters
        characters = EveManager.get_characters_from_api(api)
        for c in characters:
            try:
                EveManager.update_character_obj(c)
            except EveCharacter.DoesNotExist:
                logger.debug("API key %s has a new character on the account: %s" % (api.api_id, c))
                EveManager.create_character_obj(c, api.user, api.api_id)
        current_chars = EveCharacter.objects.filter(api_id=api.api_id)
        for c in current_chars:
            if not int(c.character_id) in [c.id for c in characters]:
                logger.info("Character %s no longer found on API ID %s" % (c, api.api_id))
                c.delete()
    except evelink.api.APIError as e:
        logger.warning('Received unexpected APIError (%s) while updating API %s' % (e.code, api.api_id))
    except EveApiManager.ApiInvalidError:
        logger.debug("API key %s is no longer valid; it and its characters will be deleted." % api.api_id)
        notify(api.user, "API Failed Validation", message="Your API key ID %s is no longer valid." % api.api_id,
               level="danger")
        still_valid = False
    except EveApiManager.ApiAccountValidationError:
        logger.info(
            "Determined api key %s for user %s no longer meets account access requirements." % (api.api_id, api.user))
        notify(api.user, "API Failed Validation",
               message="Your API key ID %s is no longer account-wide as required." % api.api_id, level="danger")
        still_valid = False
    except EveApiManager.ApiMaskValidationError as e:
        logger.info("Determined api key %s for user %s no longer meets minimum access mask as required." % (
            api.api_id, api.user))
        notify(api.user, "API Failed Validation",
               message="Your API key ID %s no longer meets access mask requirements. Required: %s Got: %s" % (
                   api.api_id, e.required_mask, e.api_mask), level="danger")
        still_valid = False
    except EveApiManager.ApiServerUnreachableError as e:
        logger.warn("Error updating API %s\n%s" % (api.api_id, str(e)))
    finally:
        if not still_valid:
            EveManager.delete_characters_by_api_id(api.api_id, api.user.id)
            EveManager.delete_api_key_pair(api.api_id, api.user.id)
            notify(api.user, "API Key Deleted",
                   message="Your API key ID %s is invalid. It and its associated characters have been deleted." % api.api_id,
                   level="danger")
Exemplo n.º 20
0
def update_alliance(id):
    alliance = EveAllianceInfo.objects.get(alliance_id=id)
    corps = EveCorporationInfo.objects.filter(alliance=alliance)
    logger.debug("Updating alliance %s with %s member corps" % (alliance, len(corps)))
    allianceinfo = EveApiManager.get_alliance_information(alliance.alliance_id)
    if allianceinfo:
        EveManager.update_alliance_info(allianceinfo['id'], allianceinfo['executor_id'],
                                        allianceinfo['member_count'], alliance.is_blue)
        for corp in corps:
            if corp.corporation_id in allianceinfo['member_corps'] is False:
                logger.info("Corp %s no longer in alliance %s" % (corp, alliance))
                corp.alliance = None
                corp.save()
        populate_alliance(alliance.alliance_id, blue=alliance.is_blue)
    elif EveApiManager.check_if_alliance_exists(alliance.alliance_id) is False:
        logger.info("Alliance %s has closed. Deleting model" % alliance)
        alliance.delete()
Exemplo n.º 21
0
 def get_characters_from_api(api):
     char_result = EveApiManager.get_characters_from_api(
         api.api_id, api.api_key).result
     provider = EveXmlProvider(adapter=EveManager.get_adapter())
     return [
         provider._build_character(result)
         for id, result in char_result.items()
     ]
Exemplo n.º 22
0
def update_alliance(id):
    alliance = EveAllianceInfo.objects.get(alliance_id=id)
    corps = EveCorporationInfo.objects.filter(alliance=alliance)
    logger.debug("Updating alliance %s with %s member corps" % (alliance, len(corps)))
    allianceinfo = EveApiManager.get_alliance_information(alliance.alliance_id)
    if allianceinfo:
        EveManager.update_alliance_info(allianceinfo['id'], allianceinfo['executor_id'],
                                        allianceinfo['member_count'], alliance.is_blue)
        for corp in corps:
            if corp.corporation_id in allianceinfo['member_corps'] is False:
                logger.info("Corp %s no longer in alliance %s" % (corp, alliance))
                corp.alliance = None
                corp.save()
        populate_alliance(alliance.alliance_id, blue=alliance.is_blue)
    elif EveApiManager.check_if_alliance_exists(alliance.alliance_id) is False:
        logger.info("Alliance %s has closed. Deleting model" % alliance)
        alliance.delete()
Exemplo n.º 23
0
    def clean(self):
        super(UpdateKeyForm, self).clean()

        if "api_id" in self.cleaned_data and "api_key" in self.cleaned_data:
            try:
                if EveManager.check_if_api_key_pair_exist(self.cleaned_data["api_id"]):
                    logger.debug(
                        "UpdateKeyForm failed cleaning as API id %s already exists." % self.cleaned_data["api_id"]
                    )
                    raise forms.ValidationError(u"API key already exist")
                if EveApiManager.api_key_is_valid(self.cleaned_data["api_id"], self.cleaned_data["api_key"]) is False:
                    raise forms.ValidationError(u"API key is invalid")
                chars = EveApiManager.get_characters_from_api(
                    self.cleaned_data["api_id"], self.cleaned_data["api_key"]
                ).result
                states = []
                states.append(self.user_state)
                for char in chars:
                    evechar = EveCharacter()
                    evechar.character_name = chars[char]["name"]
                    evechar.corporation_id = chars[char]["corp"]["id"]
                    evechar.alliance_id = chars[char]["alliance"]["id"]
                    state = determine_membership_by_character(evechar)
                    logger.debug("API ID %s character %s has state %s" % (self.cleaned_data["api_id"], evechar, state))
                    states.append(state)

                if "MEMBER" in states:
                    if (
                        EveApiManager.validate_member_api(self.cleaned_data["api_id"], self.cleaned_data["api_key"])
                        is False
                    ):
                        raise forms.ValidationError(u"API must meet member requirements")
                if "BLUE" in states:
                    if (
                        EveApiManager.validate_blue_api(self.cleaned_data["api_id"], self.cleaned_data["api_key"])
                        is False
                    ):
                        raise forms.ValidationError(u"API must meet blue requirements")
                return self.cleaned_data
            except evelink.api.APIError as e:
                logger.debug("Got error code %s while validating API %s" % (e.code, self.cleaned_data["api_id"]))
                if int(e.code) in [221, 222]:
                    raise forms.ValidationError("API key failed validation")
                else:
                    raise forms.ValidationError("Failed to reach API servers")
Exemplo n.º 24
0
def run_api_refresh():
    users = User.objects.all()

    for user in users:
        # Check if the api server is online
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            if api_key_pairs:
                valid_key = False
                authserviceinfo = AuthServicesInfo.objects.get(user=user)

                print 'Running update on user: '******'Running on ' + api_key_pair.api_id + ':' + api_key_pair.api_key
                            if EveApiManager.api_key_is_valid(api_key_pair.api_id, api_key_pair.api_key):
                                # Update characters
                                characters = EveApiManager.get_characters_from_api(api_key_pair.api_id,
                                                                                   api_key_pair.api_key)
                                EveManager.update_characters_from_list(characters)
                                valid_key = True
                            else:
                                EveManager.delete_characters_by_api_id(api_key_pair.api_id, user)
                                EveManager.delete_api_key_pair(api_key_pair.api_id, api_key_pair.api_key)

                        if valid_key:
                            # Check our main character
                            character = EveManager.get_character_by_id(authserviceinfo.main_char_id)
                            corp = EveManager.get_corporation_info_by_id(character.corporation_id)
                            main_alliance_id = EveManager.get_charater_alliance_id_by_id(authserviceinfo.main_char_id)
                            if main_alliance_id == settings.ALLIANCE_ID:
                                pass
                            elif corp is not None:
                                if corp.is_blue is not True:
                                    deactivate_services(user)
                            else:
                                deactivate_services(user)
                        else:
                            # nuke it
                            deactivate_services(user)
                else:
                    print 'No main_char_id set'
Exemplo n.º 25
0
def run_databaseUpdate():
    users = User.objects.all()
    for user in users:
        groups = user.groups.all()
        syncgroups = SyncGroupCache.objects.filter(user=user)
        add_to_databases(user, groups, syncgroups)
        remove_from_databases(user, groups, syncgroups)

    # no point if slack isn't enabled
    # this isn't really going to run every minute
    # cache will stop it
    if SlackManager.enabled():
        if EveApiManager.check_if_api_server_online():
            kill_api = EveApiManager.get_corp_kills(settings.ALLIANCE_EXEC_CORP_ID, settings.ALLIANCE_EXEC_CORP_VCODE)
            for kill in kill_api.result:
                if not EveManager.check_corporation_kill(kill):
                    # if sent save to db
                    if SlackManager.send_kill(kill):
                        EveManager.create_corporation_kill(kill)
Exemplo n.º 26
0
def corputils_search(request, corpid=settings.CORP_ID):
    logger.debug("corputils_search called by user %s" % request.user)

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)

    if request.method == 'POST':
        form = CorputilsSearchForm(request.POST)
        logger.debug("Request type POST contains form valid: %s" % form.is_valid())
        if form.is_valid():
            # Really dumb search and only checks character name
            # This can be improved but it does the job for now
            searchstring = form.cleaned_data['search_string']
            logger.debug("Searching for player with character name %s for user %s" % (searchstring, request.user))

            if settings.IS_CORP:
                try:
                    member_list = EveApiManager.get_corp_membertracking(settings.CORP_API_ID, settings.CORP_API_VCODE)
                except APIError:
                    logger.debug("Corp API does not have membertracking scope, using EveWho data instead.")
                    member_list = EveWhoManager.get_corporation_members(corpid)
            else:
                member_list = EveWhoManager.get_corporation_members(corpid)

            Member = namedtuple('Member', ['name', 'main', 'api_registered'])

            members = []
            for memberid, member_data in member_list.items():
                if searchstring.lower() in member_data["name"].lower():
                    try:
                        char = EveCharacter.objects.get(character_name=member_data["name"])
                        user = char.user
                        mainid = int(AuthServicesInfoManager.get_auth_service_info(user=user).main_char_id)
                        mainname = EveCharacter.objects.get(character_id=mainid).character_name
                        api_registered = True
                    except EveCharacter.DoesNotExist:
                        api_registered = False
                        mainname = ""
                    members.append(Member(name=member_data["name"], main=mainname, api_registered=api_registered))


            logger.info("Found %s members for user %s matching search string %s" % (len(members), request.user, searchstring))

            context = {'corp': corp, 'members': members, 'search_form': CorputilsSearchForm()}

            return render_to_response('registered/corputilssearchview.html',
                                      context, context_instance=RequestContext(request))
        else:
            logger.debug("Form invalid - returning for user %s to retry." % request.user)
            context = {'corp': corp, 'members': None, 'search_form': CorputilsSearchForm()}
            return render_to_response('registered/corputilssearchview.html',
                                      context, context_instance=RequestContext(request))

    else:
        logger.debug("Returning empty search form for user %s" % request.user)
        return HttpResponseRedirect("/corputils/")
Exemplo n.º 27
0
    def clean(self):
        super(UpdateKeyForm, self).clean()

        if 'api_id' in self.cleaned_data and 'api_key' in self.cleaned_data:
            if EveManager.check_if_api_key_pair_exist(
                    self.cleaned_data['api_id']):
                logger.debug(
                    "UpdateKeyForm failed cleaning as API id %s already exists."
                    % self.cleaned_data['api_id'])
                raise forms.ValidationError(u'API key already exist')
            if EveApiManager.api_key_is_valid(
                    self.cleaned_data['api_id'],
                    self.cleaned_data['api_key']) is False:
                raise forms.ValidationError(u'API key is invalid')
            chars = EveApiManager.get_characters_from_api(
                self.cleaned_data['api_id'],
                self.cleaned_data['api_key']).result
            states = []
            states.append(self.user_state)
            for char in chars:
                evechar = EveCharacter()
                evechar.character_name = chars[char]['name']
                evechar.corporation_id = chars[char]['corp']['id']
                evechar.alliance_id = chars[char]['alliance']['id']
                state = determine_membership_by_character(evechar)
                logger.debug("API ID %s character %s has state %s" %
                             (self.cleaned_data['api_id'], evechar, state))
                states.append(state)

            if 'MEMBER' in states:
                if EveApiManager.validate_member_api(
                        self.cleaned_data['api_id'],
                        self.cleaned_data['api_key']) is False:
                    raise forms.ValidationError(
                        u'API must meet member requirements')
            if 'BLUE' in states:
                if EveApiManager.validate_blue_api(
                        self.cleaned_data['api_id'],
                        self.cleaned_data['api_key']) is False:
                    raise forms.ValidationError(
                        u'API must meet blue requirements')
        return self.cleaned_data
Exemplo n.º 28
0
    def clean(self):
        super(UpdateKeyForm, self).clean()

        if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
            logger.debug("UpdateKeyForm failed cleaning as API id %s already exists." % self.cleaned_data['api_id'])
            if EveApiKeyPair.objects.get(api_id=self.cleaned_data['api_id']).user:
                # allow orphaned APIs to proceed to SSO validation upon re-entry
                raise forms.ValidationError('API key already exist')
        if settings.REJECT_OLD_APIS and not EveManager.check_if_api_key_pair_is_new(
                        self.cleaned_data['api_id'],
                        settings.REJECT_OLD_APIS_MARGIN):
            raise forms.ValidationError('API key is too old. Please create a new key')
        try:
            EveApiManager.validate_api(self.cleaned_data['api_id'], self.cleaned_data['api_key'], self.user)
            return self.cleaned_data
        except EveApiManager.ApiValidationError as e:
            raise forms.ValidationError(str(e))
        except evelink.api.APIError as e:
            logger.debug("Got error code %s while validating API %s" % (e.code, self.cleaned_data['api_id']))
            raise forms.ValidationError('Error while checking API key (%s)' % e.code)
Exemplo n.º 29
0
    def clean(self):
        if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
            raise forms.ValidationError(u'API key already exist')

        check_blue = False
        try:
            check_blue = self.cleaned_data['is_blue']
        except:
            pass

        if not check_blue:
            if not EveApiManager.check_api_is_type_account(self.cleaned_data['api_id'],
                                                           self.cleaned_data['api_key']):
                raise forms.ValidationError(u'API not of type account')

            if not EveApiManager.check_api_is_full(self.cleaned_data['api_id'],
                                                   self.cleaned_data['api_key']):
                raise forms.ValidationError(u'API supplied is not a full api key')

        return self.cleaned_data
Exemplo n.º 30
0
 def update_characters_from_list(chars):
     for char in chars.result:
         if EveManager.check_if_character_exist(chars.result[char]['name']):
             eve_char = EveManager.get_character_by_character_name(chars.result[char]['name'])
             eve_char.corporation_id = chars.result[char]['corp']['id']
             eve_char.corporation_name = chars.result[char]['corp']['name']
             eve_char.corporation_ticker = EveApiManager.get_corporation_ticker_from_id(
                 chars.result[char]['corp']['id'])
             eve_char.alliance_id = chars.result[char]['alliance']['id']
             eve_char.alliance_name = chars.result[char]['alliance']['name']
             eve_char.save()
Exemplo n.º 31
0
    def clean(self):
        if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
            raise forms.ValidationError(u'API key already exist')

        check_blue = False
        try:
            check_blue = self.cleaned_data['is_blue']
        except:
            pass

        if not check_blue:
            if not EveApiManager.check_api_is_type_account(self.cleaned_data['api_id'],
                                                           self.cleaned_data['api_key']):
                raise forms.ValidationError(u'API not of type account')

            if not EveApiManager.check_api_is_full(self.cleaned_data['api_id'],
                                                   self.cleaned_data['api_key']):
                raise forms.ValidationError(u'API supplied is not a full api key')

        return self.cleaned_data
Exemplo n.º 32
0
    def clean(self):
        super(UpdateKeyForm, self).clean()

        if 'api_id' in self.cleaned_data and 'api_key' in self.cleaned_data:
            try:
                if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
                    logger.debug("UpdateKeyForm failed cleaning as API id %s already exists." % self.cleaned_data['api_id'])
                    raise forms.ValidationError(u'API key already exist')
                if EveApiManager.api_key_is_valid(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                    raise forms.ValidationError(u'API key is invalid')
                if (settings.REJECT_OLD_APIS and
                    EveManager.check_if_api_key_pair_is_new(self.cleaned_data['api_id'], settings.REJECT_OLD_APIS_MARGIN) is False):
                    raise forms.ValidationError(u'API key is too old. Please create a new key')
                chars = EveApiManager.get_characters_from_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']).result
                states = []
                states.append(self.user_state)
                for char in chars:
                    evechar = EveCharacter()
                    evechar.character_name = chars[char]['name']
                    evechar.corporation_id = chars[char]['corp']['id']
                    evechar.alliance_id = chars[char]['alliance']['id']
                    state = determine_membership_by_character(evechar)
                    logger.debug("API ID %s character %s has state %s" % (self.cleaned_data['api_id'], evechar, state))
                    states.append(state)

                if 'MEMBER' in states:
                    if EveApiManager.validate_member_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                        raise forms.ValidationError(u'API must meet member requirements')
                if 'BLUE' in states:
                    if EveApiManager.validate_blue_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                        raise forms.ValidationError(u'API must meet blue requirements')
                if 'BLUE_10' in states:
                    if EveApiManager.validate_blue_api(self.cleaned_data['api_id'], self.cleaned_data['api_key']) is False:
                        raise forms.ValidationError(u'API must meet blue requirements')
                return self.cleaned_data
            except evelink.api.APIError as e:
                logger.debug("Got error code %s while validating API %s" % (e.code, self.cleaned_data['api_id']))
                if int(e.code) in [221, 222]:
                    raise forms.ValidationError("API key failed validation")
                else:
                    raise forms.ValidationError("Failed to reach API servers")
Exemplo n.º 33
0
 def update_characters_from_list(chars):
     for char in chars.result:
         if EveManager.check_if_character_exist(chars.result[char]['name']):
             eve_char = EveManager.get_character_by_character_name(
                 chars.result[char]['name'])
             eve_char.corporation_id = chars.result[char]['corp']['id']
             eve_char.corporation_name = chars.result[char]['corp']['name']
             eve_char.corporation_ticker = EveApiManager.get_corporation_ticker_from_id(
                 chars.result[char]['corp']['id'])
             eve_char.alliance_id = chars.result[char]['alliance']['id']
             eve_char.alliance_name = chars.result[char]['alliance']['name']
             eve_char.save()
Exemplo n.º 34
0
def populate_alliance(id, blue=False):
    logger.debug("Populating alliance model with id %s blue %s" % (id, blue))
    alliance_info = EveApiManager.get_alliance_information(id)

    if not alliance_info:
        raise ValueError("Supplied alliance id %s is invalid" % id)

    if not EveAllianceInfo.objects.filter(alliance_id=id).exists():
        EveManager.create_alliance_info(alliance_info['id'], alliance_info['name'], alliance_info['ticker'],
                                        alliance_info['executor_id'], alliance_info['member_count'], blue)
    alliance = EveAllianceInfo.objects.get(alliance_id=id)
    for member_corp in alliance_info['member_corps']:
        if EveCorporationInfo.objects.filter(corporation_id=member_corp).exists():
            corp = EveCorporationInfo.objects.get(corporation_id=member_corp)
            if corp.alliance != alliance:
                corp.alliance = alliance
                corp.save()
        else:
            logger.info("Creating new alliance member corp id %s" % member_corp)
            corpinfo = EveApiManager.get_corporation_information(member_corp)
            EveManager.create_corporation_info(corpinfo['id'], corpinfo['name'], corpinfo['ticker'],
                                               corpinfo['members']['current'], blue, alliance)
Exemplo n.º 35
0
 def create_characters_from_list(chars, user, api_id):
     logger.debug("Creating characters from batch: %s" % chars.result)
     for char in chars.result:
         if not EveManager.check_if_character_exist(
                 chars.result[char]['name']):
             EveManager.create_character(
                 chars.result[char]['id'], chars.result[char]['name'],
                 chars.result[char]['corp']['id'],
                 chars.result[char]['corp']['name'],
                 EveApiManager.get_corporation_ticker_from_id(
                     chars.result[char]['corp']['id']),
                 chars.result[char]['alliance']['id'],
                 chars.result[char]['alliance']['name'], user, api_id)
Exemplo n.º 36
0
    def create_characters_from_list(chars, user, api_id):

        for char in chars.result:
            if not EveManager.check_if_character_exist(chars.result[char]['name']):
                EveManager.create_character(chars.result[char]['id'],
                                            chars.result[char]['name'],
                                            chars.result[char]['corp']['id'],
                                            chars.result[char]['corp']['name'],
                                            EveApiManager.get_corporation_ticker_from_id(
                                                chars.result[char]['corp']['id']),
                                            chars.result[char]['alliance']['id'],
                                            chars.result[char]['alliance']['name'],
                                            user, api_id)
Exemplo n.º 37
0
    def clean(self):
        if 'api_id' not in self.cleaned_data or 'api_key' not in self.cleaned_data:
            # need to check if api_id and vcode in cleaned_data because
            # if they fail, they get removed from the dict but this method still happens
            return self.cleaned_data

        if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
            logger.debug("UpdateKeyForm failed cleaning as API id %s already exists." % self.cleaned_data['api_id'])
            if EveApiKeyPair.objects.get(api_id=self.cleaned_data['api_id']).user:
                # allow orphaned APIs to proceed to SSO validation upon re-entry
                raise forms.ValidationError('API key already exist')
        if settings.REJECT_OLD_APIS and not EveManager.check_if_api_key_pair_is_new(
                        self.cleaned_data['api_id'],
                        settings.REJECT_OLD_APIS_MARGIN):
            raise forms.ValidationError('API key is too old. Please create a new key')
        try:
            EveApiManager.validate_api(self.cleaned_data['api_id'], self.cleaned_data['api_key'], self.user)
            return self.cleaned_data
        except EveApiManager.ApiValidationError as e:
            raise forms.ValidationError(str(e))
        except evelink.api.APIError as e:
            logger.debug("Got error code %s while validating API %s" % (e.code, self.cleaned_data['api_id']))
            raise forms.ValidationError('Error while checking API key (%s)' % e.code)
Exemplo n.º 38
0
def refresh_api(api_key_pair):
    logger.debug("Running update on api key %s" % api_key_pair.api_id)
    user = api_key_pair.user
    if EveApiManager.api_key_is_valid(api_key_pair.api_id, api_key_pair.api_key):
        #check to ensure API key meets min spec
        logger.info("Determined api key %s is still active." % api_key_pair.api_id)
        still_valid = True
        state = determine_membership_by_user(user)
        if state == "BLUE":
            if settings.BLUE_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for blue user %s is no longer type account as requred." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s is not account-wide as required." % api_key_pair.api_id, level="danger")
                if not EveApiManager.check_blue_api_is_full(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for blue user %s no longer meets minimum access mask as required." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s does not meet access mask requirements." % api_key_pair.api_id, level="danger")
        elif state == "MEMBER":
            if settings.MEMBER_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for user %s is no longer type account as required." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s is not account-wide as required." % api_key_pair.api_id, level="danger")
                if not EveApiManager.check_api_is_full(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for user %s no longer meets minimum access mask as required." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s does not meet access mask requirements." % api_key_pair.api_id, level="danger")
        if not still_valid:
           logger.debug("API key %s has failed validation; it and its characters will be deleted." % api_key_pair.api_id)
           EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
           EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
           notify(user, "API Key Deleted", message="Your API key ID %s has failed validation. It and its associated characters have been deleted." % api_key_pair.api_id, level="danger")
        else:
           logger.info("Determined api key %s still meets requirements." % api_key_pair.api_id)
           # Update characters
           characters = EveApiManager.get_characters_from_api(api_key_pair.api_id, api_key_pair.api_key)
           EveManager.update_characters_from_list(characters)
           new_character = False
           for char in characters.result:
               # Ensure we have a model for all characters on key
               if not EveManager.check_if_character_exist(characters.result[char]['name']):
                   new_character = True
                   logger.debug("API key %s has a new character on the account: %s" % (api_key_pair.api_id, characters.result[char]['name']))
               if new_character:
                   logger.debug("Creating new character %s from api key %s" % (characters.result[char]['name'], api_key_pair.api_id))
                   EveManager.create_characters_from_list(characters, user, api_key_pair.api_id)
           current_chars = EveCharacter.objects.filter(api_id=api_key_pair.api_id)
           for c in current_chars:
               if not int(c.character_id) in characters.result:
                   logger.info("Character %s no longer found on API ID %s" % (c, api_key_pair.api_id))
                   c.delete()
    else:
        logger.debug("API key %s is no longer valid; it and its characters will be deleted." % api_key_pair.api_id)
        EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
        EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
        notify(user, "API Key Deleted", message="Your API key ID %s is invalid. It and its associated characters have been deleted." % api_key_pair.api_id, level="danger")
Exemplo n.º 39
0
def refresh_api(api_key_pair):
    logger.debug("Running update on api key %s" % api_key_pair.api_id)
    user = api_key_pair.user
    if EveApiManager.api_key_is_valid(api_key_pair.api_id, api_key_pair.api_key):
        #check to ensure API key meets min spec
        logger.info("Determined api key %s is still active." % api_key_pair.api_id)
        still_valid = True
        state = determine_membership_by_user(user)
        if state == "BLUE":
            if settings.BLUE_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for blue user %s is no longer type account as requred." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s is not account-wide as required." % api_key_pair.api_id, level="danger")
                if not EveApiManager.check_blue_api_is_full(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for blue user %s no longer meets minimum access mask as required." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s does not meet access mask requirements." % api_key_pair.api_id, level="danger")
        elif state == "MEMBER":
            if settings.MEMBER_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for user %s is no longer type account as required." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s is not account-wide as required." % api_key_pair.api_id, level="danger")
                if not EveApiManager.check_api_is_full(api_key_pair.api_id, api_key_pair.api_key):
                    logger.info("Determined api key %s for user %s no longer meets minimum access mask as required." % (api_key_pair.api_id, user))
                    still_valid = False
                    notify(user, "API Failed Validation", message="Your API key ID %s does not meet access mask requirements." % api_key_pair.api_id, level="danger")
        if not still_valid:
           logger.debug("API key %s has failed validation; it and its characters will be deleted." % api_key_pair.api_id)
           EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
           EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
           notify(user, "API Key Deleted", message="Your API key ID %s has failed validation. It and its associated characters have been deleted." % api_key_pair.api_id, level="danger")
        else:
           logger.info("Determined api key %s still meets requirements." % api_key_pair.api_id)
           # Update characters
           characters = EveApiManager.get_characters_from_api(api_key_pair.api_id, api_key_pair.api_key)
           EveManager.update_characters_from_list(characters)
           new_character = False
           for char in characters.result:
               # Ensure we have a model for all characters on key
               if not EveManager.check_if_character_exist(characters.result[char]['name']):
                   new_character = True
                   logger.debug("API key %s has a new character on the account: %s" % (api_key_pair.api_id, characters.result[char]['name']))
               if new_character:
                   logger.debug("Creating new character %s from api key %s" % (characters.result[char]['name'], api_key_pair.api_id))
                   EveManager.create_characters_from_list(characters, user, api_key_pair.api_id)
           current_chars = EveCharacter.objects.filter(api_id=api_key_pair.api_id)
           for c in current_chars:
               if not int(c.character_id) in characters.result:
                   logger.info("Character %s no longer found on API ID %s" % (c, api_key_pair.api_id))
                   c.delete()
    else:
        logger.debug("API key %s is no longer valid; it and its characters will be deleted." % api_key_pair.api_id)
        EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
        EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
        notify(user, "API Key Deleted", message="Your API key ID %s is invalid. It and its associated characters have been deleted." % api_key_pair.api_id, level="danger")
Exemplo n.º 40
0
    def clean(self):
        if EveManager.check_if_api_key_pair_exist(self.cleaned_data['api_id']):
            logger.debug("UpdateKeyForm failed cleaning as API id %s already exists." % self.cleaned_data['api_id'])
            raise forms.ValidationError(u'API key already exist')

        check_blue = False
        try:
            check_blue = self.cleaned_data['is_blue']
        except:
            pass

        if check_blue:
            if settings.BLUE_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(self.cleaned_data['api_id'],
                                                               self.cleaned_data['api_key']):
                    logger.debug("UpdateKeyForm failed cleaning as API id %s does not meet blue api key account requirement." % self.cleaned_data['api_id'])
                    raise forms.ValidationError(u'API not of type account')

            if not EveApiManager.check_blue_api_is_full(self.cleaned_data['api_id'],
                                                   self.cleaned_data['api_key']):
                logger.debug("UpdateKeyForm failed cleaning as API id %s does not meet minimum blue api access mask requirement." % self.cleaned_data['api_id'])
                raise forms.ValidationError(u'API supplied is too restricted. Minimum access mask is ' + str(settings.BLUE_API_MASK))

        else:
            if settings.MEMBER_API_ACCOUNT:
                if not EveApiManager.check_api_is_type_account(self.cleaned_data['api_id'],
                                                           self.cleaned_data['api_key']):
                    logger.debug("UpdateKeyForm failed cleaning as API id %s does not meet member api key account requirement." % self.cleaned_data['api_id'])
                    raise forms.ValidationError(u'API not of type account')

            if not EveApiManager.check_api_is_full(self.cleaned_data['api_id'],
                                                   self.cleaned_data['api_key']):
                logger.debug("UpdateKeyForm failed cleaning as API id %s does not meet minimum member api access mask requirement." % self.cleaned_data['api_id'])
                raise forms.ValidationError(u'API supplied is too restricted. Minimum access mask is ' + str(settings.MEMBER_API_MASK))

        return self.cleaned_data
Exemplo n.º 41
0
def api_sso_validate(request, token, api_id):
    logger.debug('api_sso_validate called by user %s for api %s' %
                 (request.user, api_id))
    api = get_object_or_404(EveApiKeyPair, api_id=api_id)
    if api.user and api.user != request.user:
        logger.warning(
            'User %s attempting to take ownership of api %s from %s' %
            (request.user, api_id, api.user))
        messages.warning(
            request,
            _('API %(apiid)s already claimed by user %(user)s') % {
                "apiid": api_id,
                "user": api.user
            })
        return redirect('auth_dashboard')
    elif api.sso_verified:
        logger.debug('API %s has already been verified.' % api_id)
        messages.info(
            request,
            _('API %(apiid)s has already been verified') % {"apiid": api_id})
        return redirect('auth_dashboard')
    logger.debug(
        'API %s has not been verified. Checking if token for %s matches.' %
        (api_id, token.character_name))
    characters = EveApiManager.get_characters_from_api(api.api_id,
                                                       api.api_key).result
    if token.character_id in characters:
        api.user = request.user
        api.sso_verified = True
        api.save()
        EveCharacter.objects.filter(character_id__in=characters).update(
            user=request.user, api_id=api_id)
        messages.success(
            request,
            _('Confirmed ownership of API %(apiid)s') % {"apiid": api.api_id})
        auth = AuthServicesInfo.objects.get(user=request.user)
        if not auth.main_char_id:
            return redirect('auth_characters')
        return redirect('auth_dashboard')
    else:
        messages.warning(
            request,
            _('%(character)s not found on API %(apiid)s. Please SSO as a character on the API.'
              ) % {
                  "character": token.character_name,
                  "apiid": api.api_id
              })
    return render(request, 'registered/apisso.html', context={'api': api})
Exemplo n.º 42
0
 def update_characters_from_list(chars):
     logger.debug("Updating characters from list: %s" % chars.result)
     for char in chars.result:
         if EveManager.check_if_character_exist(chars.result[char]['name']):
             eve_char = EveManager.get_character_by_character_name(chars.result[char]['name'])
             logger.debug("Got existing character model %s" % eve_char)
             eve_char.corporation_id = chars.result[char]['corp']['id']
             eve_char.corporation_name = chars.result[char]['corp']['name']
             eve_char.corporation_ticker = EveApiManager.get_corporation_ticker_from_id(
                 chars.result[char]['corp']['id'])
             eve_char.alliance_id = chars.result[char]['alliance']['id']
             eve_char.alliance_name = chars.result[char]['alliance']['name']
             eve_char.save()
             logger.info("Updated character model %s" % eve_char)
         else:
             logger.warn("Attempting to update non-existing character model with name %s" % chars.result[char]['name'])
Exemplo n.º 43
0
def add_api_key(request):
    logger.debug("add_api_key called by user %s" % request.user)
    if request.method == 'POST':
        form = UpdateKeyForm(request.user, request.POST)
        logger.debug("Request type POST with form valid: %s" % form.is_valid())
        if form.is_valid():
            if EveApiKeyPair.objects.filter(api_id=form.cleaned_data['api_id'],
                                            api_key=form.cleaned_data['api_key']).exists():
                # allow orphaned keys to proceed to SSO validation upon re-entry
                api_key = EveApiKeyPair.objects.get(api_id=form.cleaned_data['api_id'],
                                                   api_key=form.cleaned_data['api_key'])
            elif EveApiKeyPair.objects.filter(api_id=form.cleaned_data['api_id']).exists():
                logger.warn('API %s re-added with different vcode.' % form.cleaned_data['api_id'])
                EveApiKeyPair.objects.filter(api_id=form.cleaned_data['api_id']).delete()
                api_key = EveApiKeyPair.objects.create(api_id=form.cleaned_data['api_id'],
                                                       api_key=form.cleaned_data['api_key'])
            else:
                api_key = EveApiKeyPair.objects.create(api_id=form.cleaned_data['api_id'],
                                                       api_key=form.cleaned_data['api_key'])
            owner = None
            if not settings.API_SSO_VALIDATION:
                # set API and character owners if SSO validation not requested
                api_key.user = request.user
                api_key.save()
                owner = request.user
            # Grab characters associated with the key pair
            characters = EveApiManager.get_characters_from_api(form.cleaned_data['api_id'],
                                                               form.cleaned_data['api_key'])
            EveManager.create_characters_from_list(characters, owner, form.cleaned_data['api_id'])
            logger.info("Successfully processed api add form for user %s" % request.user)
            if not settings.API_SSO_VALIDATION:
                messages.success(request, 'Added API key %s to your account.' % form.cleaned_data['api_id'])
                auth = AuthServicesInfo.objects.get_or_create(user=request.user)[0]
                if not auth.main_char_id:
                    return redirect('auth_characters')
                return redirect("/api_key_management/")
            else:
                logger.debug('Requesting SSO validation of API %s by user %s' % (api_key.api_id, request.user))
                return render(request, 'registered/apisso.html', context={'api':api_key})
        else:
            logger.debug("Form invalid: returning to form.")
    else:
        logger.debug("Providing empty update key form for user %s" % request.user)
        form = UpdateKeyForm(request.user)
    context = {'form': form, 'apikeypairs': EveManager.get_api_key_pairs(request.user.id)}
    return render(request, 'registered/addapikey.html', context=context)
Exemplo n.º 44
0
def add_api_key(request):
    if request.method == 'POST':
        form = UpdateKeyForm(request.POST)

        if form.is_valid():
            EveManager.create_api_keypair(form.cleaned_data['api_id'],
                                          form.cleaned_data['api_key'],
                                          request.user)

            # Grab characters associated with the key pair
            characters = EveApiManager.get_characters_from_api(form.cleaned_data['api_id'],
                                                               form.cleaned_data['api_key'])
            EveManager.create_characters_from_list(characters, request.user, form.cleaned_data['api_id'])
            return HttpResponseRedirect("/api_key_management/")
    else:
        form = UpdateKeyForm()
    context = {'form': form, 'apikeypairs': EveManager.get_api_key_pairs(request.user.id)}
    return render_to_response('registered/addapikey.html', context,
                              context_instance=RequestContext(request))
Exemplo n.º 45
0
def run_api_refresh():
    users = User.objects.all()
    logger.debug("Running api refresh on %s users." % len(users))
    for user in users:
        # Check if the api server is online
        logger.debug("Running api refresh for user %s" % user)
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            logger.debug("User %s has api key pairs %s" % (user, api_key_pairs))
            if api_key_pairs:
                authserviceinfo, c = AuthServicesInfo.objects.get_or_create(user=user)
                logger.debug("User %s has api keys. Proceeding to refresh." % user)
                for api_key_pair in api_key_pairs:
                    refresh_api(api_key_pair)
                # Check our main character
                if EveCharacter.objects.filter(character_id=authserviceinfo.main_char_id).exists() is False:
                    logger.info("User %s main character id %s missing model. Clearning main character." % (user, authserviceinfo.main_char_id))
                    authserviceinfo.main_char_id = ''
                    authserviceinfo.save()
        set_state(user)
Exemplo n.º 46
0
def run_api_refresh():
    users = User.objects.all()
    logger.debug("Running api refresh on %s users." % len(users))
    for user in users:
        # Check if the api server is online
        logger.debug("Running api refresh for user %s" % user)
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            logger.debug("User %s has api key pairs %s" % (user, api_key_pairs))
            if api_key_pairs:
                authserviceinfo, c = AuthServicesInfo.objects.get_or_create(user=user)
                logger.debug("User %s has api keys. Proceeding to refresh." % user)
                for api_key_pair in api_key_pairs:
                    refresh_api(api_key_pair)
                # Check our main character
                if EveCharacter.objects.filter(character_id=authserviceinfo.main_char_id).exists() is False:
                    logger.info("User %s main character id %s missing model. Clearning main character." % (user, authserviceinfo.main_char_id))
                    authserviceinfo.main_char_id = ''
                    authserviceinfo.save()
                    notify(user, "Main Character Reset", message="Your specified main character no longer has a model.\nThis could be the result of an invalid API\nYour main character ID has been reset." % api_key_pair.api_id, level="warn")
        set_state(user)
Exemplo n.º 47
0
def add_api_key(request):
    if request.method == 'POST':
        form = UpdateKeyForm(request.POST)

        if form.is_valid():
            EveManager.create_api_keypair(form.cleaned_data['api_id'],
                                          form.cleaned_data['api_key'],
                                          request.user)

            # Grab characters associated with the key pair
            characters = EveApiManager.get_characters_from_api(
                form.cleaned_data['api_id'], form.cleaned_data['api_key'])
            EveManager.create_characters_from_list(characters, request.user,
                                                   form.cleaned_data['api_id'])
            return HttpResponseRedirect("/api_key_management/")
    else:
        form = UpdateKeyForm()
    context = {
        'form': form,
        'apikeypairs': EveManager.get_api_key_pairs(request.user.id)
    }
    return render_to_response('registered/addapikey.html',
                              context,
                              context_instance=RequestContext(request))
Exemplo n.º 48
0
def corp_member_view(request, corpid=None):
    logger.debug("corp_member_view called by user %s" % request.user)

    try:
        user_main = EveCharacter.objects.get(
            character_id=AuthServicesInfoManager.get_auth_service_info(
                user=request.user).main_char_id)
        user_corp_id = int(user_main.corporation_id)
    except (ValueError, EveCharacter.DoesNotExist):
        user_corp_id = settings.CORP_ID

    if not settings.IS_CORP:
        alliance = EveAllianceInfo.objects.get(
            alliance_id=settings.ALLIANCE_ID)
        alliancecorps = EveCorporationInfo.objects.filter(alliance=alliance)
        membercorplist = [(int(membercorp.corporation_id),
                           str(membercorp.corporation_name))
                          for membercorp in alliancecorps]
        membercorplist.sort(key=lambda tup: tup[1])
        membercorp_id_list = [
            int(membercorp.corporation_id) for membercorp in alliancecorps
        ]

        bluecorps = EveCorporationInfo.objects.filter(is_blue=True)
        bluecorplist = [(int(bluecorp.corporation_id),
                         str(bluecorp.corporation_name))
                        for bluecorp in bluecorps]
        bluecorplist.sort(key=lambda tup: tup[1])
        bluecorp_id_list = [
            int(bluecorp.corporation_id) for bluecorp in bluecorps
        ]

        if not (user_corp_id in membercorp_id_list
                or user_corp_id not in bluecorp_id_list):
            user_corp_id = None

    if not corpid:
        if (settings.IS_CORP):
            corpid = settings.CORP_ID
        elif user_corp_id:
            corpid = user_corp_id
        else:
            corpid = membercorplist[0][0]

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)
    Player = namedtuple(
        "Player", ["main", "maincorp", "maincorpid", "altlist", "apilist"])

    if check_if_user_has_permission(request.user, 'alliance_apis') or (
            check_if_user_has_permission(request.user, 'corp_apis') and
        (user_corp_id == corpid)):
        logger.debug("Retreiving and sending API-information")

        if settings.IS_CORP:
            try:
                member_list = EveApiManager.get_corp_membertracking(
                    settings.CORP_API_ID, settings.CORP_API_VCODE)
            except APIError:
                logger.debug(
                    "Corp API does not have membertracking scope, using EveWho data instead."
                )
                member_list = EveWhoManager.get_corporation_members(corpid)
        else:
            member_list = EveWhoManager.get_corporation_members(corpid)

        characters_with_api = {}
        characters_without_api = {}

        num_registered_characters = 0
        for char_id, member_data in member_list.items():
            try:
                char = EveCharacter.objects.get(character_id=char_id)
                char_owner = char.user
                try:
                    mainid = int(
                        AuthServicesInfoManager.get_auth_service_info(
                            user=char_owner).main_char_id)
                    mainchar = EveCharacter.objects.get(character_id=mainid)
                    mainname = mainchar.character_name
                    maincorp = mainchar.corporation_name
                    maincorpid = mainchar.corporation_id
                    api_pair = EveApiKeyPair.objects.get(api_id=char.api_id)
                except (ValueError, EveCharacter.DoesNotExist,
                        EveApiKeyPair.DoesNotExist):
                    logger.info(
                        "No main character seem to be set for character %s" %
                        char.character_name)
                    mainname = "User: "******"Not set."
                    maincorpid = None
                    api_pair = None
                num_registered_characters = num_registered_characters + 1
                characters_with_api.setdefault(
                    mainname,
                    Player(main=mainchar,
                           maincorp=maincorp,
                           maincorpid=maincorpid,
                           altlist=[],
                           apilist=[])).altlist.append(char)
                if api_pair:
                    characters_with_api[mainname].apilist.append(api_pair)

            except (EveCharacter.DoesNotExist):
                characters_without_api.update(
                    {member_data["name"]: member_data["id"]})

        for char in EveCharacter.objects.filter(corporation_id=corpid):
            if not int(char.character_id) in member_list:
                logger.info("Character '%s' does not exist in EveWho dump." %
                            char.character_name)
                char_owner = char.user
                try:
                    mainid = int(
                        AuthServicesInfoManager.get_auth_service_info(
                            user=char_owner).main_char_id)
                    mainchar = EveCharacter.objects.get(character_id=mainid)
                    mainname = mainchar.character_name
                    maincorp = mainchar.corporation_name
                    maincorpid = mainchar.corporation_id
                    api_pair = EveApiKeyPair.objects.get(api_id=char.api_id)
                except (ValueError, EveCharacter.DoesNotExist,
                        EveApiKeyPair.DoesNotExist):
                    logger.info(
                        "No main character seem to be set for character %s" %
                        char.character_name)
                    mainname = "User: "******"Not set."
                    maincorpid = None
                    api_pair = None
                num_registered_characters = num_registered_characters + 1
                characters_with_api.setdefault(
                    mainname,
                    Player(main=mainchar,
                           maincorp=maincorp,
                           maincorpid=maincorpid,
                           altlist=[],
                           apilist=[])).altlist.append(char)
                if api_pair:
                    characters_with_api[mainname].apilist.append(api_pair)

        n_unacounted = corp.member_count - (num_registered_characters +
                                            len(characters_without_api))

        if not settings.IS_CORP:
            context = {
                "membercorplist": membercorplist,
                "corp": corp,
                "characters_with_api": sorted(characters_with_api.items()),
                'n_registered': num_registered_characters,
                'n_unacounted': n_unacounted,
                "characters_without_api":
                sorted(characters_without_api.items()),
                "search_form": CorputilsSearchForm()
            }
        else:
            logger.debug("corp_member_view running in corportation mode")
            context = {
                "corp": corp,
                "characters_with_api": sorted(characters_with_api.items()),
                'n_registered': num_registered_characters,
                'n_unacounted': n_unacounted,
                "characters_without_api":
                sorted(characters_without_api.items()),
                "search_form": CorputilsSearchForm()
            }

        return render_to_response('registered/corputils.html',
                                  context,
                                  context_instance=RequestContext(request))
    return HttpResponseRedirect("/dashboard/")
Exemplo n.º 49
0
def corputils_search(request, corpid=settings.CORP_ID):
    logger.debug("corputils_search called by user %s" % request.user)

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)

    authorized = False
    try:
        user_main = EveCharacter.objects.get(
            character_id=AuthServicesInfoManager.get_auth_service_info(
                user=request.user).main_char_id)
        if check_if_user_has_permission(request.user, 'alliance_apis') or (
                check_if_user_has_permission(request.user, 'corp_apis') and
            (user_main.corporation_id == corpid)):
            logger.debug("Retreiving and sending API-information")
            authorized = True
    except (ValueError, EveCharacter.DoesNotExist):
        if check_if_user_has_permission(request.user, 'alliance_apis'):
            logger.debug("Retreiving and sending API-information")
            authorized = True

    if authorized:
        if request.method == 'POST':
            form = CorputilsSearchForm(request.POST)
            logger.debug("Request type POST contains form valid: %s" %
                         form.is_valid())
            if form.is_valid():
                # Really dumb search and only checks character name
                # This can be improved but it does the job for now
                searchstring = form.cleaned_data['search_string']
                logger.debug(
                    "Searching for player with character name %s for user %s" %
                    (searchstring, request.user))

                if settings.IS_CORP:
                    try:
                        member_list = EveApiManager.get_corp_membertracking(
                            settings.CORP_API_ID, settings.CORP_API_VCODE)
                    except APIError:
                        logger.debug(
                            "Corp API does not have membertracking scope, using EveWho data instead."
                        )
                        member_list = EveWhoManager.get_corporation_members(
                            corpid)
                else:
                    member_list = EveWhoManager.get_corporation_members(corpid)

                SearchResult = namedtuple('SearchResult', [
                    'name', 'id', 'main', 'api_registered', 'character',
                    'apiinfo'
                ])

                searchresults = []
                for memberid, member_data in member_list.items():
                    if searchstring.lower() in member_data["name"].lower():
                        try:
                            char = EveCharacter.objects.get(
                                character_name=member_data["name"])
                            user = char.user
                            mainid = int(
                                AuthServicesInfoManager.get_auth_service_info(
                                    user=user).main_char_id)
                            mainname = EveCharacter.objects.get(
                                character_id=mainid).character_name
                            api_registered = True
                            apiinfo = EveApiKeyPair.objects.get(
                                api_id=char.api_id)
                        except EveCharacter.DoesNotExist:
                            api_registered = False
                            char = None
                            mainname = ""
                            apiinfo = None

                        searchresults.append(
                            SearchResult(name=member_data["name"],
                                         id=memberid,
                                         main=mainname,
                                         api_registered=api_registered,
                                         character=char,
                                         apiinfo=apiinfo))

                logger.info(
                    "Found %s members for user %s matching search string %s" %
                    (len(searchresults), request.user, searchstring))

                context = {
                    'corp': corp,
                    'results': searchresults,
                    'search_form': CorputilsSearchForm()
                }

                return render_to_response(
                    'registered/corputilssearchview.html',
                    context,
                    context_instance=RequestContext(request))
            else:
                logger.debug("Form invalid - returning for user %s to retry." %
                             request.user)
                context = {
                    'corp': corp,
                    'members': None,
                    'search_form': CorputilsSearchForm()
                }
                return render_to_response(
                    'registered/corputilssearchview.html',
                    context,
                    context_instance=RequestContext(request))

        else:
            logger.debug("Returning empty search form for user %s" %
                         request.user)
            return HttpResponseRedirect("/corputils/")
    return HttpResponseRedirect("/dashboard/")
Exemplo n.º 50
0
def run_corp_update():
    if not EveApiManager.check_if_api_server_online():
        logger.warn(
            "Aborted updating corp and alliance models: API server unreachable"
        )
        return

    # generate member corps
    for corp_id in settings.STR_CORP_IDS + settings.STR_BLUE_CORP_IDS:
        is_blue = True if corp_id in settings.STR_BLUE_CORP_IDS else False
        try:
            if EveCorporationInfo.objects.filter(
                    corporation_id=corp_id).exists():
                update_corp(corp_id, is_blue=is_blue)
            else:
                EveManager.create_corporation(corp_id, is_blue=is_blue)
        except ObjectNotFound:
            logger.warn('Bad corp ID in settings: %s' % corp_id)

    # generate member alliances
    for alliance_id in settings.STR_ALLIANCE_IDS + settings.STR_BLUE_ALLIANCE_IDS:
        is_blue = True if alliance_id in settings.STR_BLUE_ALLIANCE_IDS else False
        try:
            if EveAllianceInfo.objects.filter(
                    alliance_id=alliance_id).exists():
                logger.debug(
                    "Updating existing owner alliance model with id %s" %
                    alliance_id)
                update_alliance(alliance_id, is_blue=is_blue)
            else:
                EveManager.create_alliance(alliance_id, is_blue=is_blue)
                EveManager.populate_alliance(alliance_id)
        except ObjectNotFound:
            logger.warn('Bad alliance ID in settings: %s' % alliance_id)

    # update existing corp models
    for corp in EveCorporationInfo.objects.exclude(
            corporation_id__in=settings.STR_CORP_IDS +
            settings.STR_BLUE_CORP_IDS):
        update_corp.delay(corp.corporation_id)

    # update existing alliance models
    for alliance in EveAllianceInfo.objects.exclude(
            alliance_id__in=settings.STR_ALLIANCE_IDS +
            settings.STR_BLUE_ALLIANCE_IDS):
        update_alliance.delay(alliance.alliance_id)

    try:
        # create standings
        standings = EveApiManager.get_corp_standings()
        if standings:
            standings = standings[settings.STANDING_LEVEL]
            for standing in standings:
                if float(standings[standing]
                         ['standing']) >= settings.BLUE_STANDING:
                    logger.debug("Standing %s meets threshold" % standing)
                    if EveApiManager.check_if_id_is_alliance(standing):
                        logger.debug("Standing %s is an alliance" % standing)
                        if EveAllianceInfo.objects.filter(
                                alliance_id=standing).exists():
                            alliance = EveAllianceInfo.objects.get(
                                alliance_id=standing)
                            if alliance.is_blue is not True:
                                logger.info("Updating alliance %s as blue" %
                                            alliance)
                                alliance.is_blue = True
                                alliance.save()
                        else:
                            EveManager.create_alliance(standing, is_blue=True)
                    elif EveApiManager.check_if_id_is_corp(standing):
                        logger.debug("Standing %s is a corp" % standing)
                        if EveCorporationInfo.objects.filter(
                                corporation_id=standing).exists():
                            corp = EveCorporationInfo.objects.get(
                                corporation_id=standing)
                            if corp.is_blue is not True:
                                logger.info("Updating corp %s as blue" % corp)
                                corp.is_blue = True
                                corp.save()
                        else:
                            logger.info(
                                "Creating model for blue corp with id %s" %
                                standing)
                            EveManager.create_corporation(standing,
                                                          is_blue=True)

        # update alliance standings
        for alliance in EveAllianceInfo.objects.filter(is_blue=True):
            if int(alliance.alliance_id) in standings:
                if float(standings[int(
                        alliance.alliance_id)]['standing']) < float(
                            settings.BLUE_STANDING):
                    logger.info(
                        "Alliance %s no longer meets minimum blue standing threshold"
                        % alliance)
                    alliance.is_blue = False
                    alliance.save()
            elif alliance.alliance_id not in settings.STR_BLUE_ALLIANCE_IDS:
                logger.info("Alliance %s no longer in standings" % alliance)
                alliance.is_blue = False
                alliance.save()

        # update corp standings
        for corp in EveCorporationInfo.objects.filter(is_blue=True):
            if int(corp.corporation_id) in standings:
                if float(standings[int(
                        corp.corporation_id)]['standing']) < float(
                            settings.BLUE_STANDING):
                    logger.info(
                        "Corp %s no longer meets minimum blue standing threshold"
                        % corp)
                    corp.is_blue = False
                    corp.save()
            elif corp.corporation_id not in settings.STR_BLUE_CORP_IDS:
                if corp.alliance:
                    if not corp.alliance.is_blue:
                        logger.info(
                            "Corp %s and its alliance %s are no longer blue" %
                            (corp, corp.alliance))
                        corp.is_blue = False
                        corp.save()
                else:
                    logger.info("Corp %s is no longer blue" % corp)
                    corp.is_blue = False
                    corp.save()
    except evelink.api.APIError as e:
        logger.error("Model update failed with error code %s" % e.code)

    # delete unnecessary alliance models
    EveAllianceInfo.objects.filter(is_blue=False).exclude(
        alliance_id__in=settings.STR_ALLIANCE_IDS).delete()

    # delete unnecessary corp models
    EveCorporationInfo.objects.filter(is_blue=False).exclude(
        corporation_id__in=settings.STR_CORP_IDS).exclude(
            alliance__alliance_id__in=settings.STR_ALLIANCE_IDS).delete()
Exemplo n.º 51
0
def corputils_search(request, corpid=settings.CORP_ID):
    logger.debug("corputils_search called by user %s" % request.user)

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)

    authorized = False
    try:
        user_main = EveCharacter.objects.get(
            character_id=AuthServicesInfo.objects.get_or_create(user=request.user)[0].main_char_id)
        if request.user.has_perm('auth.alliance_apis') or (
                    request.user.has_perm('auth.corp_apis') and (user_main.corporation_id == corpid)):
            logger.debug("Retreiving and sending API-information")
            authorized = True
    except (ValueError, EveCharacter.DoesNotExist):
        if request.user.has_perm('auth.alliance_apis'):
            logger.debug("Retrieving and sending API-information")
            authorized = True

    if authorized:
        if request.method == 'POST':
            form = CorputilsSearchForm(request.POST)
            logger.debug("Request type POST contains form valid: %s" % form.is_valid())
            if form.is_valid():
                # Really dumb search and only checks character name
                # This can be improved but it does the job for now
                searchstring = form.cleaned_data['search_string']
                logger.debug("Searching for player with character name %s for user %s" % (searchstring, request.user))

                member_list = {}
                if settings.IS_CORP:
                    member_list = EveApiManager.get_corp_membertracking(settings.CORP_API_ID, settings.CORP_API_VCODE)
                if not member_list:
                    logger.debug('Unable to fetch members from API. Pulling from EveWho')
                    member_list = EveWhoManager.get_corporation_members(corpid)

                SearchResult = namedtuple('SearchResult',
                                          ['name', 'id', 'main', 'api_registered', 'character', 'apiinfo'])

                searchresults = []
                for memberid, member_data in member_list.items():
                    if searchstring.lower() in member_data["name"].lower():
                        try:
                            char = EveCharacter.objects.get(character_name=member_data["name"])
                            user = char.user
                            mainid = int(AuthServicesInfo.objects.get_or_create(user=user)[0].main_char_id)
                            main = EveCharacter.objects.get(character_id=mainid)
                            if can_see_api(request.user, char):
                                api_registered = True
                                apiinfo = EveApiKeyPair.objects.get(api_id=char.api_id)
                            else:
                                api_registered = False
                                apiinfo = None
                        except EveCharacter.DoesNotExist:
                            api_registered = False
                            char = None
                            main = ""
                            apiinfo = None

                        searchresults.append(SearchResult(name=member_data["name"], id=memberid, main=main,
                                                          api_registered=api_registered,
                                                          character=char, apiinfo=apiinfo))

                logger.info("Found %s members for user %s matching search string %s" % (
                    len(searchresults), request.user, searchstring))

                context = {'corp': corp, 'results': searchresults, 'search_form': CorputilsSearchForm(),
                           "year": datetime.datetime.now().year, "month": datetime.datetime.now().month}

                return render(request, 'registered/corputilssearchview.html',
                              context=context)
            else:
                logger.debug("Form invalid - returning for user %s to retry." % request.user)
                context = {'corp': corp, 'members': None, 'search_form': CorputilsSearchForm()}
                return render(request, 'registered/corputilssearchview.html', context=context)

        else:
            logger.debug("Returning empty search form for user %s" % request.user)
            return redirect("auth_corputils")
    else:
        logger.warn('User %s not authorized to view corp stats for corp ID %s' % (request.user, corpid))
    return redirect("auth_dashboard")
Exemplo n.º 52
0
def corp_member_view(request, corpid=None, year=datetime.date.today().year, month=datetime.date.today().month):
    year = int(year)
    month = int(month)
    start_of_month = datetime.datetime(year, month, 1)
    start_of_next_month = first_day_of_next_month(year, month)
    start_of_previous_month = first_day_of_previous_month(year, month)
    logger.debug("corp_member_view called by user %s" % request.user)

    try:
        user_main = EveCharacter.objects.get(
            character_id=AuthServicesInfo.objects.get_or_create(user=request.user)[0].main_char_id)
        user_corp_id = user_main.corporation_id
    except (ValueError, EveCharacter.DoesNotExist):
        user_corp_id = settings.CORP_ID

    if not settings.IS_CORP:
        alliance = EveAllianceInfo.objects.get(alliance_id=settings.ALLIANCE_ID)
        alliancecorps = EveCorporationInfo.objects.filter(alliance=alliance)
        membercorplist = [(int(membercorp.corporation_id), str(membercorp.corporation_name)) for membercorp in
                          alliancecorps]
        membercorplist.sort(key=lambda tup: tup[1])
        membercorp_id_list = [int(membercorp.corporation_id) for membercorp in alliancecorps]

        bluecorps = EveCorporationInfo.objects.filter(is_blue=True)
        bluecorplist = [(int(bluecorp.corporation_id), str(bluecorp.corporation_name)) for bluecorp in bluecorps]
        bluecorplist.sort(key=lambda tup: tup[1])
        bluecorp_id_list = [int(bluecorp.corporation_id) for bluecorp in bluecorps]

        if not (user_corp_id in membercorp_id_list or user_corp_id not in bluecorp_id_list):
            user_corp_id = None

    if not corpid:
        if settings.IS_CORP:
            corpid = settings.CORP_ID
        elif user_corp_id:
            corpid = user_corp_id
        else:
            corpid = membercorplist[0][0]

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)
    if request.user.has_perm('auth.alliance_apis') or (request.user.has_perm('auth.corp_apis') and user_corp_id == corpid):
        logger.debug("Retreiving and sending API-information")

        if settings.IS_CORP:
            try:
                member_list = EveApiManager.get_corp_membertracking(settings.CORP_API_ID, settings.CORP_API_VCODE)
            except APIError:
                logger.debug("Corp API does not have membertracking scope, using EveWho data instead.")
                member_list = EveWhoManager.get_corporation_members(corpid)
        else:
            member_list = EveWhoManager.get_corporation_members(corpid)

        characters_with_api = {}
        characters_without_api = {}

        num_registered_characters = 0
        for char_id, member_data in member_list.items():
            try:
                char = EveCharacter.objects.get(character_id=char_id)
                char_owner = char.user
                try:
                    mainid = int(AuthServicesInfo.objects.get_or_create(user=char_owner)[0].main_char_id)
                    mainchar = EveCharacter.objects.get(character_id=mainid)
                    mainname = mainchar.character_name
                    maincorp = mainchar.corporation_name
                    maincorpid = mainchar.corporation_id
                    api_pair = EveApiKeyPair.objects.get(api_id=char.api_id)
                except (ValueError, EveCharacter.DoesNotExist, EveApiKeyPair.DoesNotExist):
                    logger.info("No main character seem to be set for character %s" % char.character_name)
                    mainname = "User: "******"Not set."
                    maincorpid = None
                    api_pair = None
                num_registered_characters += 1
                characters_with_api.setdefault(mainname, Player(main=mainchar,
                                                                user=char_owner,
                                                                maincorp=maincorp,
                                                                maincorpid=maincorpid,
                                                                altlist=[],
                                                                apilist=[],
                                                                n_fats=0)
                                               ).altlist.append(char)
                if api_pair:
                    characters_with_api[mainname].apilist.append(api_pair)

            except EveCharacter.DoesNotExist:
                characters_without_api.update({member_data["name"]: member_data["id"]})

        for char in EveCharacter.objects.filter(corporation_id=corpid):
            if not int(char.character_id) in member_list:
                logger.info("Character '%s' does not exist in EveWho dump." % char.character_name)
                char_owner = char.user
                try:
                    mainid = int(AuthServicesInfo.objects.get_or_create(user=char_owner)[0].main_char_id)
                    mainchar = EveCharacter.objects.get(character_id=mainid)
                    mainname = mainchar.character_name
                    maincorp = mainchar.corporation_name
                    maincorpid = mainchar.corporation_id
                    api_pair = EveApiKeyPair.objects.get(api_id=char.api_id)
                except (ValueError, EveCharacter.DoesNotExist, EveApiKeyPair.DoesNotExist):
                    logger.info("No main character seem to be set for character %s" % char.character_name)
                    mainname = "User: "******"Not set."
                    maincorpid = None
                    api_pair = None
                num_registered_characters += 1
                characters_with_api.setdefault(mainname, Player(main=mainchar,
                                                                user=char_owner,
                                                                maincorp=maincorp,
                                                                maincorpid=maincorpid,
                                                                altlist=[],
                                                                apilist=[],
                                                                n_fats=0)
                                               ).altlist.append(char)
                if api_pair:
                    characters_with_api[mainname].apilist.append(api_pair)

        n_unacounted = corp.member_count - (num_registered_characters + len(characters_without_api))

        for mainname, player in characters_with_api.items():
            fats_this_month = Fat.objects.filter(user=player.user).filter(
                fatlink__fatdatetime__gte=start_of_month).filter(fatlink__fatdatetime__lt=start_of_next_month)
            characters_with_api[mainname].n_fats = len(fats_this_month)

        if start_of_next_month > datetime.datetime.now():
            start_of_next_month = None

        if not settings.IS_CORP:
            context = {"membercorplist": membercorplist,
                       "corp": corp,
                       "characters_with_api": sorted(characters_with_api.items()),
                       'n_registered': num_registered_characters,
                       'n_unacounted': n_unacounted,
                       "characters_without_api": sorted(characters_without_api.items()),
                       "search_form": CorputilsSearchForm()}
        else:
            logger.debug("corp_member_view running in corportation mode")
            context = {"corp": corp,
                       "characters_with_api": sorted(characters_with_api.items()),
                       'n_registered': num_registered_characters,
                       'n_unacounted': n_unacounted,
                       "characters_without_api": sorted(characters_without_api.items()),
                       "search_form": CorputilsSearchForm()}

        context["next_month"] = start_of_next_month
        context["previous_month"] = start_of_previous_month
        context["this_month"] = start_of_month

        return render(request, 'registered/corputils.html', context=context)
    else:
        logger.warn('User %s (%s) not authorized to view corp stats for corp id %s' % (request.user, user_corp_id, corpid))
    return redirect("auth_dashboard")
Exemplo n.º 53
0
def run_corp_update():
    if EveApiManager.check_if_api_server_online() is False:
        logger.warn(
            "Aborted updating corp and alliance models: API server unreachable"
        )
        return
    standing_level = 'alliance'
    try:
        # get corp info for owning corp if required
        ownercorpinfo = {}
        if settings.IS_CORP:
            standing_level = 'corp'
            logger.debug("Getting information for owning corp with id %s" %
                         settings.CORP_ID)
            ownercorpinfo = EveApiManager.get_corporation_information(
                settings.CORP_ID)
            if not ownercorpinfo:
                logger.error(
                    "Failed to retrieve corp info for owning corp id %s - bad corp id?"
                    % settings.CORP_ID)
                return

        # check if we need to update an alliance model
        alliance_id = ''
        if ownercorpinfo and ownercorpinfo['alliance']['id']:
            alliance_id = ownercorpinfo['alliance']['id']
        elif settings.IS_CORP is False:
            alliance_id = settings.ALLIANCE_ID

        # get and create alliance info for owning alliance if required
        alliance = None
        if alliance_id:
            logger.debug("Getting information for owning alliance with id %s" %
                         alliance_id)
            ownerallianceinfo = EveApiManager.get_alliance_information(
                alliance_id)
            if not ownerallianceinfo:
                logger.error(
                    "Failed to retrieve corp info for owning alliance id %s - bad alliance id?"
                    % alliance_id)
                return
            if EveAllianceInfo.objects.filter(
                    alliance_id=ownerallianceinfo['id']).exists():
                logger.debug(
                    "Updating existing owner alliance model with id %s" %
                    alliance_id)
                EveManager.update_alliance_info(
                    ownerallianceinfo['id'], ownerallianceinfo['executor_id'],
                    ownerallianceinfo['member_count'], False)
            else:
                populate_alliance(alliance_id)
                alliance = EveAllianceInfo.objects.get(alliance_id=alliance_id)

        # create corp info for owning corp if required
        if ownercorpinfo:
            if EveCorporationInfo.objects.filter(
                    corporation_id=ownercorpinfo['id']).exists():
                logger.debug("Updating existing owner corp model with id %s" %
                             ownercorpinfo['id'])
                EveManager.update_corporation_info(
                    ownercorpinfo['id'], ownercorpinfo['members']['current'],
                    alliance, False)
            else:
                logger.info("Creating model for owning corp with id %s" %
                            ownercorpinfo['id'])
                EveManager.create_corporation_info(
                    ownercorpinfo['id'], ownercorpinfo['name'],
                    ownercorpinfo['ticker'],
                    ownercorpinfo['members']['current'], False, alliance)

        # validate and create corp models for member corps of owning alliance
        if alliance:
            current_corps = EveCorporationInfo.objects.filter(
                alliance=alliance)
            for corp in current_corps:
                if corp.corporation_id in ownerallianceinfo[
                        'member_corps'] is False:
                    logger.info(
                        "Corp %s is no longer in owning alliance %s - updating model."
                        % (corp, alliance))
                    corp.alliance = None
                    corp.save()
            for member_corp in ownerallianceinfo['member_corps']:
                if EveCorporationInfo.objects.filter(
                        corporation_id=member_corp).exists():
                    corp = EveCorporationInfo.objects.get(
                        corporation_id=member_corp)
                    if corp.alliance == alliance is not True:
                        logger.info(
                            "Associating corp %s with owning alliance %s" %
                            (corp, alliance))
                        corp.alliance = alliance
                        corp.save()
                else:
                    corpinfo = EveApiManager.get_corporation_information(
                        member_corp)
                    logger.info(
                        "Creating model for owning alliance member corp with id %s"
                        % corpinfo['id'])
                    EveManager.create_corporation_info(
                        corpinfo['id'], corpinfo['name'], corpinfo['ticker'],
                        corpinfo['members']['current'], False, alliance)

        # update existing corp models
        for corp in EveCorporationInfo.objects.all():
            update_corp.delay(corp.corporation_id)

        # update existing alliance models
        for alliance in EveAllianceInfo.objects.all():
            update_alliance.delay(alliance.alliance_id)

        # create standings
        standings = EveApiManager.get_corp_standings()
        if standings:
            standings = standings[standing_level]
            for standing in standings:
                if int(standings[standing]
                       ['standing']) >= settings.BLUE_STANDING:
                    logger.debug("Standing %s meets threshold" % standing)
                    if EveApiManager.check_if_id_is_alliance(standing):
                        logger.debug("Standing %s is an alliance" % standing)
                        if EveAllianceInfo.objects.filter(
                                alliance_id=standing).exists():
                            alliance = EveAllianceInfo.objects.get(
                                alliance_id=standing)
                            if alliance.is_blue is not True:
                                logger.info("Updating alliance %s as blue" %
                                            alliance)
                                alliance.is_blue = True
                                alliance.save()
                        else:
                            populate_alliance(standing, blue=True)
                    elif EveApiManager.check_if_id_is_corp(standing):
                        logger.debug("Standing %s is a corp" % standing)
                        if EveCorporationInfo.objects.filter(
                                corporation_id=standing).exists():
                            corp = EveCorporationInfo.objects.get(
                                corporation_id=standing)
                            if corp.is_blue is not True:
                                logger.info("Updating corp %s as blue" % corp)
                                corp.is_blue = True
                                corp.save()
                        else:
                            logger.info(
                                "Creating model for blue corp with id %s" %
                                standing)
                            corpinfo = EveApiManager.get_corporation_information(
                                standing)
                            corp_alliance = None
                            if EveAllianceInfo.objects.filter(
                                    alliance_id=corpinfo['alliance']
                                ['id']).exists():
                                logger.debug(
                                    "New corp model for standing %s has existing alliance model"
                                    % standing)
                                corp_alliance = EveAllianceInfo.objects.get(
                                    alliance_id=corpinfo['alliance']['id'])
                            EveManager.create_corporation_info(
                                corpinfo['id'], corpinfo['name'],
                                corpinfo['ticker'],
                                corpinfo['members']['current'], True,
                                corp_alliance)

        # update alliance standings
        for alliance in EveAllianceInfo.objects.filter(is_blue=True):
            if int(alliance.alliance_id) in standings:
                if float(standings[int(
                        alliance.alliance_id)]['standing']) < float(
                            settings.BLUE_STANDING):
                    logger.info(
                        "Alliance %s no longer meets minimum blue standing threshold"
                        % alliance)
                    alliance.is_blue = False
                    alliance.save()
            else:
                logger.info("Alliance %s no longer in standings" % alliance)
                alliance.is_blue = False
                alliance.save()

        # update corp standings
        for corp in EveCorporationInfo.objects.filter(is_blue=True):
            if int(corp.corporation_id) in standings:
                if float(standings[int(
                        corp.corporation_id)]['standing']) < float(
                            settings.BLUE_STANDING):
                    logger.info(
                        "Corp %s no longer meets minimum blue standing threshold"
                        % corp)
                    corp.is_blue = False
                    corp.save()
            else:
                if corp.alliance:
                    if not corp.alliance.is_blue:
                        logger.info(
                            "Corp %s and its alliance %s are no longer blue" %
                            (corp, corp.alliance))
                        corp.is_blue = False
                        corp.save()
                else:
                    logger.info("Corp %s is no longer blue" % corp)
                    corp.is_blue = False
                    corp.save()

        # delete unnecessary alliance models
        for alliance in EveAllianceInfo.objects.filter(is_blue=False):
            logger.debug("Checking to delete alliance %s" % alliance)
            if not settings.IS_CORP:
                if not alliance.alliance_id == settings.ALLIANCE_ID:
                    logger.info("Deleting unnecessary alliance model %s" %
                                alliance)
                    alliance.delete()
            else:
                if not alliance.evecorporationinfo_set.filter(
                        corporation_id=settings.CORP_ID).exists():
                    logger.info("Deleting unnecessary alliance model %s" %
                                alliance)
                    alliance.delete()

        # delete unnecessary corp models
        for corp in EveCorporationInfo.objects.filter(is_blue=False):
            logger.debug("Checking to delete corp %s" % corp)
            if not settings.IS_CORP:
                if corp.alliance:
                    logger.debug("Corp %s has alliance %s" %
                                 (corp, corp.alliance))
                    if not corp.alliance.alliance_id == settings.ALLIANCE_ID:
                        logger.info("Deleting unnecessary corp model %s" %
                                    corp)
                        corp.delete()
                else:
                    logger.info("Deleting unnecessary corp model %s" % corp)
                    corp.delete()
            else:
                if corp.corporation_id != settings.CORP_ID:
                    logger.debug("Corp %s is not owning corp" % corp)
                    if corp.alliance:
                        logger.debug("Corp %s has alliance %s" %
                                     (corp, corp.alliance))
                        if not corp.alliance.evecorporationinfo_set.filter(
                                corporation_id=settings.CORP_ID).exists():
                            logger.info("Deleting unnecessary corp model %s" %
                                        corp)
                            corp.delete()
                    else:
                        logger.info("Deleting unnecessary corp model %s" %
                                    corp)
                        corp.delete()
                else:
                    logger.debug("Corp %s is owning corp" % corp)
    except evelink.api.APIError as e:
        logger.error("Model update failed with error code %s" % e.code)
Exemplo n.º 54
0
def corp_member_view(request, corpid=None):
    logger.debug("corp_member_view called by user %s" % request.user)

    if not settings.IS_CORP:
        alliance = EveAllianceInfo.objects.get(
            alliance_id=settings.ALLIANCE_ID)
        alliancecorps = EveCorporationInfo.objects.filter(alliance=alliance)
        membercorp_list = [(int(membercorp.corporation_id),
                            str(membercorp.corporation_name))
                           for membercorp in alliancecorps]
        membercorp_list.sort(key=lambda tup: tup[1])

    if not corpid:
        if (settings.CORP_ID):
            corpid = settings.CORP_ID
        else:
            corpid = membercorp_list[0][0]

    corp = EveCorporationInfo.objects.get(corporation_id=corpid)
    Player = namedtuple("Player",
                        ["main", "maincorp", "maincorpid", "altlist"])

    if settings.IS_CORP:
        try:
            member_list = EveApiManager.get_corp_membertracking(
                settings.CORP_API_ID, settings.CORP_API_VCODE)
        except APIError:
            logger.debug(
                "Corp API does not have membertracking scope, using EveWho data instead."
            )
            member_list = EveWhoManager.get_corporation_members(corpid)
    else:
        member_list = EveWhoManager.get_corporation_members(corpid)

    characters_with_api = {}
    characters_without_api = {}

    for char_id, member_data in member_list.items():
        try:
            char = EveCharacter.objects.get(character_id=char_id)
            user = char.user
            try:
                mainid = int(
                    AuthServicesInfoManager.get_auth_service_info(
                        user=user).main_char_id)
                mainchar = EveCharacter.objects.get(character_id=mainid)
                mainname = mainchar.character_name
                maincorp = mainchar.corporation_name
                maincorpid = mainchar.corporation_id
            except (ValueError, EveCharacter.DoesNotExist):
                mainname = "User: "******"Not set."
                maincorpid = None
            characters_with_api.setdefault(
                mainname,
                Player(main=mainchar,
                       maincorp=maincorp,
                       maincorpid=maincorpid,
                       altlist=[])).altlist.append(char)

        except EveCharacter.DoesNotExist:
            characters_without_api.update(
                {member_data["name"]: member_data["id"]})

    if not settings.IS_CORP:
        context = {
            "membercorp_list": membercorp_list,
            "corp": corp,
            "characters_with_api": sorted(characters_with_api.items()),
            "characters_without_api": sorted(characters_without_api.items()),
            "search_form": CorputilsSearchForm()
        }
    else:
        logger.debug("corp_member_view running in corportation mode")
        context = {
            "corp": corp,
            "characters_with_api": sorted(characters_with_api.items()),
            "characters_without_api": sorted(characters_without_api.items()),
            "search_form": CorputilsSearchForm()
        }

    return render_to_response('registered/corputils.html',
                              context,
                              context_instance=RequestContext(request))
Exemplo n.º 55
0
def run_corp_update():
    # I am not proud of this block of code
    if EveApiManager.check_if_api_server_online():
        logger.debug("API server online and reachable. Proceeding with corp update.")
        if settings.IS_CORP:
            # Create the corp
            logger.debug(
                "Ensuring corp model exists for owning corp id %s due to settings.IS_CORP %s"
                % (settings.CORP_ID, settings.IS_CORP)
            )
            ownercorpinfo = EveApiManager.get_corporation_information(settings.CORP_ID)
            logger.debug("Determined ownercorp info: %s" % ownercorpinfo)
            if not EveManager.check_if_corporation_exists_by_id(ownercorpinfo["id"]):
                logger.debug("Owning corp id %s does not have a model. Creating." % ownercorpinfo["id"])
                if ownercorpinfo["alliance"]["id"] is None:
                    logger.debug("Owning corp does not have an alliance. Creating model with alliance=None")
                    EveManager.create_corporation_info(
                        ownercorpinfo["id"],
                        ownercorpinfo["name"],
                        ownercorpinfo["ticker"],
                        ownercorpinfo["members"]["current"],
                        False,
                        None,
                    )
                else:
                    alliance_info = EveApiManager.get_alliance_information(ownercorpinfo["alliance"]["id"])
                    logger.debug("Owning corp has an alliance, got info: %s" % alliance_info)
                    if not EveManager.check_if_alliance_exists_by_id(ownercorpinfo["alliance"]["id"]):
                        logger.debug(
                            "Owning corp missing alliance model. Creating for id %s" % ownercorpinfo["alliance"]["id"]
                        )
                        EveManager.create_alliance_info(
                            ownercorpinfo["alliance"]["id"],
                            alliance_info["name"],
                            alliance_info["ticker"],
                            alliance_info["executor_id"],
                            alliance_info["member_count"],
                            False,
                        )
                    alliance = EveManager.get_alliance_info_by_id(ownercorpinfo["alliance"]["id"])
                    logger.debug("Got alliance model %s for owning corp. Creating corp model." % alliance)
                    EveManager.create_corporation_info(
                        ownercorpinfo["id"],
                        ownercorpinfo["name"],
                        ownercorpinfo["ticker"],
                        ownercorpinfo["members"]["current"],
                        False,
                        alliance,
                    )

        else:
            # Updated alliance info
            logger.debug("Getting info for owning alliance %s" % settings.ALLIANCE_ID)
            alliance_info = EveApiManager.get_alliance_information(settings.ALLIANCE_ID)
            logger.debug("Owning alliance info: %s" % alliance_info)
            # Populate alliance info
            if not EveManager.check_if_alliance_exists_by_id(settings.ALLIANCE_ID):
                logger.debug("Missing alliance model for owning alliance. Creating with id %s" % settings.ALLIANCE_ID)
                EveManager.create_alliance_info(
                    settings.ALLIANCE_ID,
                    alliance_info["name"],
                    alliance_info["ticker"],
                    alliance_info["executor_id"],
                    alliance_info["member_count"],
                    False,
                )
            alliance = EveManager.get_alliance_info_by_id(settings.ALLIANCE_ID)
            logger.debug("Got owning alliance model %s" % alliance)
            # Create the corps in the alliance
            for alliance_corp in alliance_info["member_corps"]:
                corpinfo = EveApiManager.get_corporation_information(alliance_corp)
                logger.debug("Got corpinfo for alliance member corp: %s" % corpinfo)
                if not EveManager.check_if_corporation_exists_by_id(corpinfo["id"]):
                    logger.debug("Alliance member corp id %s missing model - creating." % corpinfo["id"])
                    EveManager.create_corporation_info(
                        corpinfo["id"],
                        corpinfo["name"],
                        corpinfo["ticker"],
                        corpinfo["members"]["current"],
                        False,
                        alliance,
                    )

        # determine what level of standings to check
        # refer to https://github.com/eve-val/evelink/blob/master/evelink/parsing/contact_list.py#L43
        standing_level = "alliance"
        if settings.IS_CORP:
            logger.debug("Switching standings check to corp level.")
            standing_level = "corp"

        # Create the corps in the standings
        corp_standings = EveApiManager.get_corp_standings()
        logger.debug("Got %s corp standings." % len(corp_standings))
        if corp_standings:
            for standing_id in EveApiManager.get_corp_standings()[standing_level]:
                logger.debug("Processing standing id %s" % standing_id)
                if int(corp_standings[standing_level][standing_id]["standing"]) >= settings.BLUE_STANDING:
                    logger.debug("Standing %s meets or exceeds blue threshold." % standing_id)
                    if EveApiManager.check_if_id_is_character(standing_id):
                        logger.debug("Standing id %s is a character. Not creating model.")
                        pass
                    elif EveApiManager.check_if_id_is_corp(standing_id):
                        corpinfo = EveApiManager.get_corporation_information(standing_id)
                        logger.debug("Standing id %s is a corp. Got corpinfo: %s" % (standing_id, corpinfo))
                        if not EveManager.check_if_corporation_exists_by_id(standing_id):
                            logger.debug("Corp model for standing id %s does not exist. Creating" % standing_id)
                            EveManager.create_corporation_info(
                                corpinfo["id"],
                                corpinfo["name"],
                                corpinfo["ticker"],
                                corpinfo["members"]["current"],
                                True,
                                None,
                            )
                    else:
                        # Alliance id create corps
                        blue_alliance_info = EveApiManager.get_alliance_information(standing_id)
                        logger.debug(
                            "Standing id %s is alliance. Got alliance info: %s" % (standing_id, blue_alliance_info)
                        )
                        if not EveManager.check_if_alliance_exists_by_id(standing_id):
                            logger.debug("Alliance model for standing id %s does not exist. Creating" % standing_id)
                            EveManager.create_alliance_info(
                                standing_id,
                                blue_alliance_info["name"],
                                blue_alliance_info["ticker"],
                                blue_alliance_info["executor_id"],
                                blue_alliance_info["member_count"],
                                True,
                            )

                        blue_alliance = EveManager.get_alliance_info_by_id(standing_id)
                        logger.debug("Got alliance model %s for standing id %s" % (blue_alliance, standing_id))
                        for blue_alliance_corp in blue_alliance_info["member_corps"]:
                            blue_info = EveApiManager.get_corporation_information(blue_alliance_corp)
                            logger.debug(
                                "Got corpinfo for member corp id %s of blue alliance %s: %s"
                                % (blue_info["id"], blue_alliance, blue_info)
                            )
                            if not EveManager.check_if_corporation_exists_by_id(blue_info["id"]):
                                logger.debug(
                                    "Blue alliance %s member corp id %s missing model. Creating."
                                    % (blue_alliance, blue_info["id"])
                                )
                                EveManager.create_corporation_info(
                                    blue_info["id"],
                                    blue_info["name"],
                                    blue_info["ticker"],
                                    blue_info["members"]["current"],
                                    True,
                                    blue_alliance,
                                )

            # Update all allinace info's
            for all_alliance_info in EveManager.get_all_alliance_info():
                logger.debug("Validating alliance model %s" % all_alliance_info)
                if EveApiManager.check_if_alliance_exists(all_alliance_info.alliance_id):
                    all_alliance_api_info = EveApiManager.get_alliance_information(all_alliance_info.alliance_id)
                    logger.debug("Got alliance %s alliance info: %s" % (all_alliance_info, all_alliance_api_info))
                    if not settings.IS_CORP and all_alliance_info.alliance_id == settings.ALLIANCE_ID:
                        logger.debug("Alliance %s is owning alliance. Updating info." % all_alliance_info)
                        EveManager.update_alliance_info(
                            all_alliance_api_info["id"],
                            all_alliance_api_info["executor_id"],
                            all_alliance_api_info["member_count"],
                            False,
                        )
                    elif standing_level in corp_standings:
                        if int(all_alliance_info.alliance_id) in corp_standings[standing_level]:
                            if (
                                int(corp_standings[standing_level][int(all_alliance_info.alliance_id)]["standing"])
                                >= settings.BLUE_STANDING
                            ):
                                logger.debug("Alliance %s is blue. Updating." % all_alliance_info)
                                EveManager.update_alliance_info(
                                    all_alliance_api_info["id"],
                                    all_alliance_api_info["executor_id"],
                                    all_alliance_api_info["member_count"],
                                    True,
                                )
                            else:
                                logger.debug(
                                    "Alliance %s does not meet blue standing threshold. Updating as non-blue."
                                    % all_alliance_info
                                )
                                EveManager.update_alliance_info(
                                    all_alliance_api_info["id"],
                                    all_alliance_api_info["executor_id"],
                                    all_alliance_api_info["member_count"],
                                    False,
                                )
                        else:
                            logger.debug("Alliance %s not in standings. Updating as non-blue." % all_alliance_info)
                            EveManager.update_alliance_info(
                                all_alliance_api_info["id"],
                                all_alliance_api_info["executor_id"],
                                all_alliance_api_info["member_count"],
                                False,
                            )
                    else:
                        logger.debug("No standings found. Updating alliance %s as non-blue." % all_alliance_info)
                        EveManager.update_alliance_info(
                            all_alliance_api_info["id"],
                            all_alliance_api_info["executor_id"],
                            all_alliance_api_info["member_count"],
                            False,
                        )
                else:
                    logger.info("Alliance %s has closed. Deleting model." % all_alliance_info)
                    # alliance no longer exists
                    all_alliance_info.delete()

            # Update corp infos
            for all_corp_info in EveManager.get_all_corporation_info():
                logger.debug("Validating corp model %s" % all_corp_info)
                if EveApiManager.check_if_corp_exists(all_corp_info.corporation_id):
                    alliance = None
                    corpinfo = EveApiManager.get_corporation_information(all_corp_info.corporation_id)
                    if corpinfo["alliance"]["id"] is not None:
                        alliance = EveManager.get_alliance_info_by_id(corpinfo["alliance"]["id"])
                    logger.debug("Got corpinfo %s and allianceinfo %s" % (corpinfo, alliance))

                    if settings.IS_CORP and all_corp_info.corporation_id == settings.CORP_ID:
                        logger.debug("Corp %s is owning corp. Updating." % all_corp_info)
                        EveManager.update_corporation_info(corpinfo["id"], corpinfo["members"]["current"], None, False)
                    elif int(all_corp_info.corporation_id) in corp_standings[standing_level]:
                        if (
                            int(corp_standings[standing_level][int(all_corp_info.corporation_id)]["standing"])
                            >= settings.BLUE_STANDING
                        ):
                            logger.debug("Corp %s is blue. Updating." % all_corp_info)
                            EveManager.update_corporation_info(
                                corpinfo["id"], corpinfo["members"]["current"], None, True
                            )
                        else:
                            logger.debug(
                                "Corp %s does not meet blue standing threshold. Updating as non-blue." % all_corp_info
                            )
                            EveManager.update_corporation_info(
                                corpinfo["id"], corpinfo["members"]["current"], None, False
                            )
                    elif alliance is not None and all_corp_info.alliance is not None:
                        logger.debug(
                            "Corp %s not in standings - checking alliance with model %s" % (all_corp_info, alliance)
                        )
                        if (not settings.IS_CORP) and (all_corp_info.alliance.alliance_id == settings.ALLIANCE_ID):
                            logger.debug("Corp %s is member of owning alliance. Updating." % all_corp_info)
                            EveManager.update_corporation_info(
                                corpinfo["id"], corpinfo["members"]["current"], alliance, False
                            )
                        elif int(alliance.alliance_id) in corp_standings[standing_level]:
                            if (
                                int(corp_standings[standing_level][int(alliance.alliance_id)]["standing"])
                                >= settings.BLUE_STANDING
                            ):
                                logger.debug("Corp %s alliance %s is blue. Updating." % (all_corp_info, alliance))
                                EveManager.update_corporation_info(
                                    corpinfo["id"], corpinfo["members"]["current"], alliance, True
                                )
                            else:
                                logger.debug(
                                    "Corp %s alliance %s does not meet blue standing threshold. Updating as non-blue."
                                    % (all_corp_info, alliance)
                                )
                                EveManager.update_corporation_info(
                                    corpinfo["id"], corpinfo["members"]["current"], alliance, False
                                )
                        else:
                            logger.debug(
                                "Corp %s alliance %s not found in standings. Updating as non-blue."
                                % (all_corp_info, alliance)
                            )
                            EveManager.update_corporation_info(
                                corpinfo["id"], corpinfo["members"]["current"], alliance, False
                            )
                    else:
                        logger.info(
                            "Corp model %s is not owning, member of owning alliance, or in standings. Updating as non-blue."
                            % all_corp_info
                        )
                        EveManager.update_corporation_info(corpinfo["id"], corpinfo["members"]["current"], None, False)
                else:
                    # corp has closed
                    logger.info("Corp %s has closed. Deleting model." % all_corp_info)
                    all_corp_info.delete()

        # Remove irrelevent corp and alliance models
        # Check the corps
        for all_corp_info in EveManager.get_all_corporation_info():
            logger.debug("Checking to delete corp model %s" % all_corp_info)
            if settings.IS_CORP:
                if all_corp_info.corporation_id != settings.CORP_ID:
                    if not all_corp_info.is_blue:
                        logger.info("Corp model %s is not owning corp nor blue. Deleting." % all_corp_info)
                        all_corp_info.delete()
            else:
                if all_corp_info.alliance is not None:
                    if all_corp_info.alliance.alliance_id != settings.ALLIANCE_ID:
                        if not all_corp_info.is_blue:
                            logger.info("Corp model %s not in owning alliance nor blue. Deleting." % all_corp_info)
                            all_corp_info.delete()
                elif not all_corp_info.is_blue:
                    logger.info("Corp model %s has no alliance and is not blue. Deleting." % all_corp_info)
                    all_corp_info.delete()

        # Check the alliances
        for all_alliance_info in EveManager.get_all_alliance_info():
            logger.debug("Checking to delete alliance model %s" % all_alliance_info)
            if settings.IS_CORP:
                if all_alliance_info.is_blue is not True:
                    if ownercorpinfo["alliance"]["id"] is not None:
                        if int(all_alliance_info.alliance_id) != ownercorpinfo["alliance"]["id"]:
                            logger.info(
                                "Alliance model %s not owning corp alliance nor blue. Deleting." % all_alliance_info
                            )
                            all_alliance_info.delete()
                    else:
                        logger.info(
                            "Alliance model %s not blue to alliance-less owning corp. Deleting." % all_alliance_info
                        )
                        all_alliance_info.delete()
            elif all_alliance_info.alliance_id != settings.ALLIANCE_ID:
                if all_alliance_info.is_blue is not True:
                    logger.info("Alliance model %s not owning alliance nor blue. Deleting." % all_alliance_info)
                    all_alliance_info.delete()
Exemplo n.º 56
0
def run_api_refresh():
    users = User.objects.all()
    logger.debug("Running api refresh on %s users." % len(users))
    for user in users:
        # Check if the api server is online
        logger.debug("Running api refresh for user %s" % user)
        if EveApiManager.check_if_api_server_online():
            api_key_pairs = EveManager.get_api_key_pairs(user.id)
            logger.debug("User %s has api key pairs %s" % (user, api_key_pairs))
            if api_key_pairs:
                authserviceinfo, c = AuthServicesInfo.objects.get_or_create(user=user)
                logger.debug("User %s has api keys. Proceeding to refresh." % user)
                for api_key_pair in api_key_pairs:
                    logger.debug("Running update on api key %s" % api_key_pair.api_id)
                    if EveApiManager.api_key_is_valid(api_key_pair.api_id, api_key_pair.api_key):
                        # check to ensure API key meets min spec
                        logger.info("Determined api key %s is still active." % api_key_pair.api_id)
                        still_valid = True
                        state = determine_membership_by_user(user)
                        if state == "BLUE":
                            if settings.BLUE_API_ACCOUNT:
                                type = EveApiManager.check_api_is_type_account(
                                    api_key_pair.api_id, api_key_pair.api_key
                                )
                                if type == None:
                                    api_key_pair.error_count += 1
                                    api_key_pair.save()
                                    logger.info(
                                        "API key %s incurred an error checking if type account. Error count is now %s"
                                        % (api_key_pair.api_id, api_key_pair.error_count)
                                    )
                                    still_valid = None
                                elif type == False:
                                    logger.info(
                                        "Determined api key %s for blue user %s is no longer type account as requred."
                                        % (api_key_pair.api_id, user)
                                    )
                                    still_valid = False
                            full = EveApiManager.check_blue_api_is_full(api_key_pair.api_id, api_key_pair.api_key)
                            if full == None:
                                api_key_pair.error_count += 1
                                api_key_pair.save()
                                logger.info(
                                    "API key %s incurred an error checking if meets mask requirements. Error count is now %s"
                                    % (api_key_pair.api_id, api_key_pair.error_count)
                                )
                                still_valid = None
                            elif full == False:
                                logger.info(
                                    "Determined api key %s for blue user %s no longer meets minimum access mask as required."
                                    % (api_key_pair.api_id, user)
                                )
                                still_valid = False
                        elif state == "MEMBER":
                            if settings.MEMBER_API_ACCOUNT:
                                type = EveApiManager.check_api_is_type_account(
                                    api_key_pair.api_id, api_key_pair.api_key
                                )
                                if type == None:
                                    api_key_pair.error_count += 1
                                    api_key_pair.save()
                                    logger.info(
                                        "API key %s incurred an error checking if type account. Error count is now %s"
                                        % (api_key_pair.api_id, api_key_pair.error_count)
                                    )
                                    still_valid = None
                                elif type == False:
                                    logger.info(
                                        "Determined api key %s for user %s is no longer type account as required."
                                        % (api_key_pair.api_id, user)
                                    )
                                    still_valid = False
                            full = EveApiManager.check_api_is_full(api_key_pair.api_id, api_key_pair.api_key)
                            if full == None:
                                api_key_pair.error_count += 1
                                api_key_pair.save()
                                logger.info(
                                    "API key %s incurred an error checking if meets mask requirements. Error count is now %s"
                                    % (api_key_pair.api_id, api_key_pair.error_count)
                                )
                                still_valid = None
                            elif full == False:
                                logger.info(
                                    "Determined api key %s for user %s no longer meets minimum access mask as required."
                                    % (api_key_pair.api_id, user)
                                )
                                still_valid = False
                        if still_valid == None:
                            if api_key_pair.error_count >= 3:
                                logger.info(
                                    "API key %s has incurred 3 or more errors. Assuming invalid." % api_key_pair.api_id
                                )
                                still_valid = False
                        if still_valid == False:
                            logger.debug(
                                "API key %s has failed validation; it and its characters will be deleted."
                                % api_key_pair.api_id
                            )
                            EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
                            EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
                        elif still_valid == True:
                            if api_key_pair.error_count != 0:
                                logger.info(
                                    "Clearing error count for api %s as it passed validation" % api_key_pair.api_id
                                )
                                api_key_pair.error_count = 0
                                api_key_pair.save()
                            logger.info("Determined api key %s still meets requirements." % api_key_pair.api_id)
                            # Update characters
                            characters = EveApiManager.get_characters_from_api(
                                api_key_pair.api_id, api_key_pair.api_key
                            )
                            EveManager.update_characters_from_list(characters)
                            new_character = False
                            for char in characters.result:
                                # Ensure we have a model for all characters on key
                                if not EveManager.check_if_character_exist(characters.result[char]["name"]):
                                    new_character = True
                                    logger.debug(
                                        "API key %s has a new character on the account: %s"
                                        % (api_key_pair.api_id, characters.result[char]["name"])
                                    )
                            if new_character:
                                logger.debug(
                                    "Creating new character %s from api key %s"
                                    % (characters.result[char]["name"], api_key_pair.api_id)
                                )
                                EveManager.create_characters_from_list(characters, user, api_key_pair.api_key)
                    else:
                        logger.debug(
                            "API key %s is no longer valid; it and its characters will be deleted."
                            % api_key_pair.api_id
                        )
                        EveManager.delete_characters_by_api_id(api_key_pair.api_id, user.id)
                        EveManager.delete_api_key_pair(api_key_pair.api_id, user.id)
                # Check our main character
                if EveCharacter.objects.filter(character_id=authserviceinfo.main_char_id).exists() is False:
                    logger.info(
                        "User %s main character id %s missing model. Clearning main character."
                        % (user, authserviceinfo.main_char_id)
                    )
                    authserviceinfo.main_char_id = ""
                    authserviceinfo.save()
                else:
                    logger.warn("User %s has no main character id, unable to validate membership.")
        set_state(user)
Exemplo n.º 57
0
def add_api_key(request):
    logger.debug("add_api_key called by user %s" % request.user)
    if request.method == 'POST':
        form = UpdateKeyForm(request.user, request.POST)
        logger.debug("Request type POST with form valid: %s" % form.is_valid())
        if form.is_valid():
            if EveApiKeyPair.objects.filter(
                    api_id=form.cleaned_data['api_id'],
                    api_key=form.cleaned_data['api_key']).exists():
                # allow orphaned keys to proceed to SSO validation upon re-entry
                api_key = EveApiKeyPair.objects.get(
                    api_id=form.cleaned_data['api_id'],
                    api_key=form.cleaned_data['api_key'])
            elif EveApiKeyPair.objects.filter(
                    api_id=form.cleaned_data['api_id']).exists():
                logger.warn('API %s re-added with different vcode.' %
                            form.cleaned_data['api_id'])
                EveApiKeyPair.objects.filter(
                    api_id=form.cleaned_data['api_id']).delete()
                api_key = EveApiKeyPair.objects.create(
                    api_id=form.cleaned_data['api_id'],
                    api_key=form.cleaned_data['api_key'])
            else:
                api_key = EveApiKeyPair.objects.create(
                    api_id=form.cleaned_data['api_id'],
                    api_key=form.cleaned_data['api_key'])
            owner = None
            if not settings.API_SSO_VALIDATION:
                # set API and character owners if SSO validation not requested
                api_key.user = request.user
                api_key.save()
                owner = request.user
            # Grab characters associated with the key pair
            characters = EveApiManager.get_characters_from_api(
                form.cleaned_data['api_id'], form.cleaned_data['api_key'])
            EveManager.create_characters_from_list(characters, owner,
                                                   form.cleaned_data['api_id'])
            logger.info("Successfully processed api add form for user %s" %
                        request.user)
            if not settings.API_SSO_VALIDATION:
                messages.success(
                    request, 'Added API key %s to your account.' %
                    form.cleaned_data['api_id'])
                auth = AuthServicesInfo.objects.get_or_create(
                    user=request.user)[0]
                if not auth.main_char_id:
                    return redirect('auth_characters')
                return redirect("/api_key_management/")
            else:
                logger.debug('Requesting SSO validation of API %s by user %s' %
                             (api_key.api_id, request.user))
                return render(request,
                              'registered/apisso.html',
                              context={'api': api_key})
        else:
            logger.debug("Form invalid: returning to form.")
    else:
        logger.debug("Providing empty update key form for user %s" %
                     request.user)
        form = UpdateKeyForm(request.user)
    context = {
        'form': form,
        'apikeypairs': EveManager.get_api_key_pairs(request.user.id)
    }
    return render(request, 'registered/addapikey.html', context=context)
Exemplo n.º 58
0
def run_alliance_corp_update():
    # I am not proud of this block of code
    if EveApiManager.check_if_api_server_online():

        # Updated alliance info
        alliance_info = EveApiManager.get_alliance_information(
            settings.ALLIANCE_ID)

        # Populate alliance info
        if not EveManager.check_if_alliance_exists_by_id(settings.ALLIANCE_ID):
            EveManager.create_alliance_info(settings.ALLIANCE_ID,
                                            alliance_info['name'],
                                            alliance_info['ticker'],
                                            alliance_info['executor_id'],
                                            alliance_info['member_count'],
                                            False)

        alliance = EveManager.get_alliance_info_by_id(settings.ALLIANCE_ID)

        # Create the corps in the alliance
        for alliance_corp in alliance_info['member_corps']:
            corpinfo = EveApiManager.get_corporation_information(alliance_corp)
            if not EveManager.check_if_corporation_exists_by_id(
                    corpinfo['id']):
                EveManager.create_corporation_info(
                    corpinfo['id'], corpinfo['name'], corpinfo['ticker'],
                    corpinfo['members']['current'], False, alliance)

        # Create the corps in the standings
        alliance_standings = EveApiManager.get_alliance_standings()
        if alliance_standings:
            for standing_id in EveApiManager.get_alliance_standings(
            )['alliance']:
                if int(alliance_standings['alliance'][standing_id]
                       ['standing']) >= settings.ALLIANCE_BLUE_STANDING:
                    if EveApiManager.check_if_id_is_character(standing_id):
                        pass
                    elif EveApiManager.check_if_id_is_corp(standing_id):
                        corpinfo = EveApiManager.get_corporation_information(
                            standing_id)
                        if not EveManager.check_if_corporation_exists_by_id(
                                standing_id):
                            EveManager.create_corporation_info(
                                corpinfo['id'], corpinfo['name'],
                                corpinfo['ticker'],
                                corpinfo['members']['current'], True, None)
                    else:
                        # Alliance id create corps
                        blue_alliance_info = EveApiManager.get_alliance_information(
                            standing_id)

                        if not EveManager.check_if_alliance_exists_by_id(
                                standing_id):
                            EveManager.create_alliance_info(
                                standing_id, blue_alliance_info['name'],
                                blue_alliance_info['ticker'],
                                blue_alliance_info['executor_id'],
                                blue_alliance_info['member_count'], True)

                        blue_alliance = EveManager.get_alliance_info_by_id(
                            standing_id)

                        for blue_alliance_corp in blue_alliance_info[
                                'member_corps']:
                            blue_info = EveApiManager.get_corporation_information(
                                blue_alliance_corp)
                            if not EveManager.check_if_corporation_exists_by_id(
                                    blue_info['id']):
                                EveManager.create_corporation_info(
                                    blue_info['id'], blue_info['name'],
                                    blue_info['ticker'],
                                    blue_info['members']['current'], True,
                                    blue_alliance)

        # Update all allinace info's
        for all_alliance_info in EveManager.get_all_alliance_info():
            all_alliance_api_info = EveApiManager.get_alliance_information(
                all_alliance_info.alliance_id)
            if all_alliance_info.alliance_id == settings.ALLIANCE_ID:
                EveManager.update_alliance_info(
                    all_alliance_api_info['id'],
                    all_alliance_api_info['executor_id'],
                    all_alliance_api_info['member_count'], False)
            else:
                if 'alliance' in alliance_standings:
                    if int(all_alliance_info.alliance_id
                           ) in alliance_standings['alliance']:
                        if int(alliance_standings['alliance'][int(
                                all_alliance_info.alliance_id)]['standing']
                               ) >= settings.ALLIANCE_BLUE_STANDING:
                            EveManager.update_alliance_info(
                                all_alliance_api_info['id'],
                                all_alliance_api_info['executor_id'],
                                all_alliance_api_info['member_count'], True)
                        else:
                            EveManager.update_alliance_info(
                                all_alliance_api_info['id'],
                                all_alliance_api_info['executor_id'],
                                all_alliance_api_info['member_count'], False)

                    else:
                        EveManager.update_alliance_info(
                            all_alliance_api_info['id'],
                            all_alliance_api_info['executor_id'],
                            all_alliance_api_info['member_count'], False)
                else:
                    EveManager.update_alliance_info(
                        all_alliance_api_info['id'],
                        all_alliance_api_info['executor_id'],
                        all_alliance_api_info['member_count'], False)

        # Update corp infos
        for all_corp_info in EveManager.get_all_corporation_info():
            alliance = None
            corpinfo = EveApiManager.get_corporation_information(
                all_corp_info.corporation_id)
            if corpinfo['alliance']['id'] is not None:
                alliance = EveManager.get_alliance_info_by_id(
                    corpinfo['alliance']['id'])

            if alliance is not None and all_corp_info.alliance is not None:

                if all_corp_info.alliance.alliance_id == settings.ALLIANCE_ID:
                    EveManager.update_corporation_info(
                        corpinfo['id'], corpinfo['members']['current'],
                        alliance, False)
                else:
                    if int(alliance.alliance_id
                           ) in alliance_standings['alliance']:
                        if int(alliance_standings['alliance'][int(
                                alliance.alliance_id)]['standing']
                               ) >= settings.ALLIANCE_BLUE_STANDING:
                            EveManager.update_corporation_info(
                                corpinfo['id'], corpinfo['members']['current'],
                                alliance, True)
                        else:
                            EveManager.update_corporation_info(
                                corpinfo['id'], corpinfo['members']['current'],
                                alliance, False)
                    else:
                        EveManager.update_corporation_info(
                            corpinfo['id'], corpinfo['members']['current'],
                            alliance, False)
            else:
                if int(all_corp_info.corporation_id
                       ) in alliance_standings['alliance']:
                    if int(alliance_standings['alliance'][int(
                            all_corp_info.corporation_id)]
                           ['standing']) >= settings.ALLIANCE_BLUE_STANDING:
                        EveManager.update_corporation_info(
                            corpinfo['id'], corpinfo['members']['current'],
                            None, True)
                    else:
                        EveManager.update_corporation_info(
                            corpinfo['id'], corpinfo['members']['current'],
                            None, False)
                else:
                    EveManager.update_corporation_info(
                        corpinfo['id'], corpinfo['members']['current'], None,
                        False)

        # Nuke the none believers
        # Check the corps
        for all_corp_info in EveManager.get_all_corporation_info():
            if all_corp_info.alliance is not None:
                if all_corp_info.alliance.alliance_id is not None:
                    if all_corp_info.alliance.alliance_id != settings.ALLIANCE_ID:
                        if not all_corp_info.is_blue:
                            all_corp_info.delete()
            else:
                if not all_corp_info.is_blue:
                    all_corp_info.delete()

        # Check the alliances
        for all_alliance_info in EveManager.get_all_alliance_info():
            if all_alliance_info.alliance_id != settings.ALLIANCE_ID:
                if all_alliance_info.is_blue is not True:
                    all_alliance_info.delete()