<commit_before>from datetime import datetime, timedelta
from xml.dom import minidom
import logging

from celery.decorators import task
from celery.task.sets import TaskSet

from eve_proxy.models import CachedDocument

from eve_api.models import EVEAccount, EVEPlayerCharacter
from eve_api.app_defines import *
from eve_api.api_exceptions import *
from eve_api.utils import basic_xml_parse_doc
from eve_api.tasks.character import import_eve_characters
from eve_api.tasks.corporation import import_corp_members, import_corp_details

from sso.tasks import update_user_access

from django.contrib.auth.models import User

@task(ignore_result=True, expires=120)
def queue_apikey_updates(update_delay=86400, batch_size=50):
    """
    Updates all Eve API elements in the database
    """

    log = queue_apikey_updates.get_logger()
    # Update all the eve accounts and related corps
    delta = timedelta(seconds=update_delay)
    log.info("Updating APIs older than %s" % (datetime.now() - delta))

    accounts = EVEAccount.objects.filter(api_last_updated__lt=(datetime.now() - delta)).exclude(api_status=API_STATUS_ACC_EXPIRED).exclude(api_status=API_STATUS_AUTH_ERROR).order_by('api_last_updated')[:batch_size]
    log.info("%s account(s) to update" % accounts.count())
    for acc in accounts:
        log.debug("Queueing UserID %s for update" % acc.api_user_id)
        if not acc.user:
            acc.delete()
            continue
        import_apikey.delay(api_key=acc.api_key, api_userid=acc.api_user_id)


@task(ignore_result=True)
def import_apikey(api_userid, api_key, user=None, force_cache=False):
    """
    Imports a EVE Account from the API, doesn't return a result
    """
    log = import_apikey.get_logger()
    try:
        import_apikey_func(api_userid, api_key, user, force_cache, log)
    except:
        log.error('Error importing API Key')

@task()
def import_apikey_result(api_userid, api_key, user=None, force_cache=False, callback=None):
    """
    Imports a EVE Account from the API and returns the account object when completed
    """

    log = import_apikey_result.get_logger()
    try:
        results = import_apikey_func(api_userid, api_key, user, force_cache, log)
    except APIAccessException, exc:
        log.error('Error importing API Key - flagging for retry')
    else:
        if callback:
            subtask(callback).delay(account=results)
        else:
            return results


def import_apikey_func(api_userid, api_key, user=None, force_cache=False, log=logging.getLogger(__name__)):
    log.info('Importing %s/%s' % (api_userid, api_key))

    auth_params = {'userid': api_userid, 'apikey': api_key}
    account_doc = CachedDocument.objects.api_query('/account/Characters.xml.aspx', params=auth_params, no_cache=force_cache)

    doc = basic_xml_parse_doc(account_doc)['eveapi']

    # Checks for a document error
    if 'error' in doc:
        try:
            account = EVEAccount.objects.get(id=api_userid)
        except EVEAccount.DoesNotExist:
            # If no Account exists in the DB, just ignore it
            return

        error = doc['error']['code']
        if int(error) >= 500:
            # API disabled, down or rejecting, return without changes
            return
        elif error in ['202', '203', '204', '205', '212']:
            account.api_status = API_STATUS_AUTH_ERROR
        elif error == '211':
            account.api_status = API_STATUS_ACC_EXPIRED
        else:
            account.api_status = API_STATUS_OTHER_ERROR
        account.api_last_updated = datetime.utcnow()
        account.save()
        return account

    # Create or retrieve the account last to make sure everything
    # before here is good to go.
    account, created = EVEAccount.objects.get_or_create(id=api_userid, api_user_id=api_userid, api_key=api_key)
    account.api_status = API_STATUS_OK
    if user and created:
        account.user = User.objects.get(id=user)

    account.api_last_updated = datetime.utcnow()
    account.save()

    # Check API keytype if we have a character and a unknown key status
    if account.api_keytype == API_KEYTYPE_UNKNOWN:
        keycheck = CachedDocument.objects.api_query('/account/AccountStatus.xml.aspx', params=auth_params, no_cache=True)
        keydoc = basic_xml_parse_doc(keycheck)['eveapi']

        if 'error' in keydoc:
            account.api_keytype = API_KEYTYPE_LIMITED
        elif not 'error' in keydoc:
            account.api_keytype = API_KEYTYPE_FULL<commit_msg>Update access when the key fails<commit_after>from datetime import datetime, timedelta
from xml.dom import minidom
import logging

from celery.decorators import task
from celery.task.sets import TaskSet

from eve_proxy.models import CachedDocument

from eve_api.models import EVEAccount, EVEPlayerCharacter
from eve_api.app_defines import *
from eve_api.api_exceptions import *
from eve_api.utils import basic_xml_parse_doc
from eve_api.tasks.character import import_eve_characters
from eve_api.tasks.corporation import import_corp_members, import_corp_details

from sso.tasks import update_user_access

from django.contrib.auth.models import User

@task(ignore_result=True, expires=120)
def queue_apikey_updates(update_delay=86400, batch_size=50):
    """
    Updates all Eve API elements in the database
    """

    log = queue_apikey_updates.get_logger()
    # Update all the eve accounts and related corps
    delta = timedelta(seconds=update_delay)
    log.info("Updating APIs older than %s" % (datetime.now() - delta))

    accounts = EVEAccount.objects.filter(api_last_updated__lt=(datetime.now() - delta)).exclude(api_status=API_STATUS_ACC_EXPIRED).exclude(api_status=API_STATUS_AUTH_ERROR).order_by('api_last_updated')[:batch_size]
    log.info("%s account(s) to update" % accounts.count())
    for acc in accounts:
        log.debug("Queueing UserID %s for update" % acc.api_user_id)
        if not acc.user:
            acc.delete()
            continue
        import_apikey.delay(api_key=acc.api_key, api_userid=acc.api_user_id)


@task(ignore_result=True)
def import_apikey(api_userid, api_key, user=None, force_cache=False):
    """
    Imports a EVE Account from the API, doesn't return a result
    """
    log = import_apikey.get_logger()
    try:
        import_apikey_func(api_userid, api_key, user, force_cache, log)
    except:
        log.error('Error importing API Key')

@task()
def import_apikey_result(api_userid, api_key, user=None, force_cache=False, callback=None):
    """
    Imports a EVE Account from the API and returns the account object when completed
    """

    log = import_apikey_result.get_logger()
    try:
        results = import_apikey_func(api_userid, api_key, user, force_cache, log)
    except APIAccessException, exc:
        log.error('Error importing API Key - flagging for retry')
    else:
        if callback:
            subtask(callback).delay(account=results)
        else:
            return results


def import_apikey_func(api_userid, api_key, user=None, force_cache=False, log=logging.getLogger(__name__)):
    log.info('Importing %s/%s' % (api_userid, api_key))

    auth_params = {'userid': api_userid, 'apikey': api_key}
    account_doc = CachedDocument.objects.api_query('/account/Characters.xml.aspx', params=auth_params, no_cache=force_cache)

    doc = basic_xml_parse_doc(account_doc)['eveapi']

    # Checks for a document error
    if 'error' in doc:
        try:
            account = EVEAccount.objects.get(id=api_userid)
        except EVEAccount.DoesNotExist:
            # If no Account exists in the DB, just ignore it
            return

        error = doc['error']['code']
        if int(error) >= 500:
            # API disabled, down or rejecting, return without changes
            return
        elif error in ['202', '203', '204', '205', '212']:
            account.api_status = API_STATUS_AUTH_ERROR
        elif error == '211':
            account.api_status = API_STATUS_ACC_EXPIRED
        else:
            account.api_status = API_STATUS_OTHER_ERROR
        account.api_last_updated = datetime.utcnow()
        account.save()
        if account.user:
            update_user_access.delay(account.user.id)
        return account

    # Create or retrieve the account last to make sure everything
    # before here is good to go.
    account, created = EVEAccount.objects.get_or_create(id=api_userid, api_user_id=api_userid, api_key=api_key)
    account.api_status = API_STATUS_OK
    if user and created:
        account.user = User.objects.get(id=user)

    account.api_last_updated = datetime.utcnow()
    account.save()

    # Check API keytype if we have a character and a unknown key status
    if account.api_keytype == API_KEYTYPE_UNKNOWN:
        keycheck = CachedDocument.objects.api_query('/account/AccountStatus.xml.aspx', params=auth_params, no_cache=True)
        keydoc = basic_xml_parse_doc(keycheck)['eveapi']

        if 'error' in keydoc:
            account.api_keytype = API_KEYTYPE_LIMITED
        elif not 'error' in keydoc:
            account.api_keytype = API_KEYTYPE_FULL
{'fraction_non_alphanumeric': 0.09039859061880642, 'fraction_numerical': 0.006826690156353226, 'mean_word_length': 3.4677816035415643, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 12}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '204804', 'n_tokens_mistral': 2891, 'n_tokens_neox': 2772, 'n_words': 685}