Esempio n. 1
0
 def __init__(self, fleet_id: int, client: EsiClient = None) -> None:
     self.__fleetID: int = fleet_id
     if client is None:
         self.__client: EsiClient = get_esi_client()
         self.__api: App = get_api()
     else:
         self.__client: EsiClient = client
         self.__api: App = get_api()
Esempio n. 2
0
 def __init__(self, client: EsiClient = None) -> None:
     if client is None:
         self.__client: EsiClient = get_esi_client(token=None,
                                                   noauth=True,
                                                   retry_request=True)
         self.__api: App = get_api()
     else:
         self.__client: EsiClient = client
         self.__api: App = get_api()
Esempio n. 3
0
def characterid_from_name(char_name: str) -> Tuple[Optional[int], Optional[str]]:
    """
    @return charid, name
    """

    api = get_api()
    security = Security(
        api,
    )

    client = EsiClient(security, timeout=10)

    search_answer = client.request(api.op['get_search'](search=char_name, categories=['character'], strict=True))
    print(search_answer.data)
    #print(search_answer.status_code)
    print(search_answer.status)
    print(search_answer)
    # this character name doesn't exist
    if not ('character' in search_answer.data):
        return None, None
    char_id: int = int(search_answer.data['character'][0])
    
    char_answer = client.request(api.op['get_characters_character_id'](character_id=char_id))
    char_name: str = char_answer.data['name']
    
    return char_id, char_name
Esempio n. 4
0
def open_information(target_id: int) -> ESIResponse:
    api_v1: App = get_api()
    client: EsiClient = get_esi_client()

    resp = client.request(api_v1.op['post_ui_openwindow_information'](target_id=target_id))
    if resp.status == 204:
        return ESIResponse(get_expire_time(resp), resp.status, None)
    return make_error_response(resp)
Esempio n. 5
0
def send_mail(token: SSOToken, recipients: List[Dict[str, Any]], body: str,
              subject: str) -> Any:
    api: App = get_api()
    client = get_esi_client(token, False)

    mail = {
        "approved_cost": 0,
        "body": body,
        "recipients": recipients,
        "subject": subject
    }
    return client.request(api.op['post_characters_character_id_mail'](
        character_id=current_user.current_char, mail=mail))
Esempio n. 6
0
def open_mail(token: SSOToken,
              recipients: Sequence[int],
              body: str,
              subject: str,
              to_corp_or_alliance_id: int = None,
              to_mailing_list_id: int = None) -> ESIResponse:
    """
    {
        "body": "string",
        "recipients": [
            0 # min 1 item
        ],
        "subject": "string",
        "to_corp_or_alliance_id": 0, # optional
        "to_mailing_list_id": 0 # optional
        # max 1 of the 2 optimal values
    }
    """

    payload: Dict[str, Any] = {}
    if to_corp_or_alliance_id is not None and to_mailing_list_id is not None:
        raise ValueError(
            "Only to_mailing_list_id or to_corp_or_alliance_id can have a value, not both!"
        )

    payload['body'] = body
    payload['subject'] = subject
    if to_mailing_list_id is not None:
        payload['to_mailing_list_id'] = to_mailing_list_id

    if to_corp_or_alliance_id is not None:
        payload['to_corp_or_alliance_id'] = to_corp_or_alliance_id

    payload['recipients'] = []

    for charID in recipients:
        payload['recipients'].append(charID)

    if len(payload['recipients']) <= 0:
        payload['recipients'] = [0]

    client = get_esi_client(token, False)
    api: App = get_api()
    response = client.request(
        api.op['post_ui_openwindow_newmail'](new_mail=payload))
    if response.status == 204:
        return ESIResponse(get_expire_time(response), response.status, None)

    return make_error_response(response)
Esempio n. 7
0
def add_system_info(system_id: int, esi_client: EsiClient) -> Optional[Tuple[int, EsiClient]]:
    try:
        api: App = get_api()
        system_request = api.op['get_universe_systems_system_id'](system_id=system_id)
        system_resp = esi_client.request(system_request)
        if system_resp.status != 200:
            logger.error(f'Could not get systen info for id={system_id} status={system_resp.status}')
            return
        system = SolarSystem()
        system.solarSystemID = system_resp.data['system_id']
        system.solarSystemName = system_resp.data['name']
        db.session.merge(system)
        db.session.commit()
        return None
    except Exception as e:
        return system_id, esi_client
Esempio n. 8
0
def add_constellation_info(const_id: int, esi_client: EsiClient) -> Optional[Tuple[int, EsiClient]]:
    try:
        api: App = get_api()
        const_request = api.op['get_universe_constellations_constellation_id'](constellation_id=const_id)

        const_resp = esi_client.request(const_request)
        if const_resp.status != 200:
            logger.error(f'Could not get constellation info for id={const_id} status={const_resp.status}')
            return
        const = Constellation()
        const.constellationID = const_resp.data['constellation_id']
        const.constellationName = const_resp.data['name']
        db.session.merge(const)
        db.session.commit()
        return None
    except Exception as e:
        return const_id, esi_client
Esempio n. 9
0
def get_esi_client_for_account(account: Account, noauth: bool = False) -> EsiClient:
    if noauth:
        return EsiClient(timeout=10, headers={'User-Agent': 'Bruce Warhead IncWaitlist/'+version})

    security = EsiSecurity(
        get_api(),
        crest_return_url,
        crest_client_id,
        crest_client_secret
    )
    security.update_token({
        'access_token': account.ssoToken.access_token,
        'expires_in': (account.ssoToken.access_token_expires -
                       datetime.utcnow()).total_seconds(),
        'refresh_token': account.ssoToken.refresh_token
    })
    return EsiClient(security, timeout=10, headers={'User-Agent': 'Bruce Warhead IncWaitlist/'+version})
def open_information(target_id: int) -> ESIResponse:
    """
    Tries to open an ingame information window for the given id.
    :param target_id: id to open ingame information window for
    :return: ESIResponse
    :raises APIException if there is something wrong with tokens
    """
    token: Optional[SSOToken] = current_user.get_a_sso_token_with_scopes(esi_scopes.open_ui_window)
    if token is None:
        return ESIResponse(datetime.datetime.utcnow(), 403, f"No token with the required scopes:"
                                                            f" {''.join(esi_scopes.open_ui_window)} exists.")
    api_v1: App = get_api()
    client: EsiClient = get_esi_client(token)

    resp = client.request(api_v1.op['post_ui_openwindow_information'](target_id=target_id))
    if resp.status == 204:
        return ESIResponse(get_expire_time(resp), resp.status, None)
    return make_error_response(resp)
Esempio n. 11
0
def get_item_data_from_api(name: str) -> Optional[any]:
    """Tries to get api data of an item with this name from Search API"""
    search_endpoint = SearchEndpoint()
    search_response: SearchResponse = search_endpoint.public_search(
        name, ['inventory_type'], True)
    result_ids = search_response.inventory_type_ids()
    if result_ids is None or len(result_ids) < 1:
        return None

    esi_client: EsiClient = get_esi_client(True)
    api = get_api()

    for result_id in result_ids:
        type_result = esi_client.request(
            api.op['get_universe_types_type_id'](type_id=result_id))
        if type_result.data.name == name:
            return type_result.data

    return None
Esempio n. 12
0
def update_systems() -> int:
    esi_client: EsiClient = get_esi_client(None, True)
    api: App = get_api()
    systems_request = api.op['get_universe_systems']()
    systems_resp = esi_client.request(systems_request)
    if systems_resp.status != 200:
        flask.abort(500, 'Could not get system ids from ESI')
    futures: List[Future] = []
    with ThreadPoolExecutor(max_workers=500) as executor:
        for system_id in systems_resp.data:
            futures.append(executor.submit(add_system_info, system_id, esi_client))
        # re request if it throws an exception
        while len(futures) > 0:
            nfutures: List[Future] = []
            for f in as_completed(futures):
                r: Optional[Tuple[int, EsiClient]] = f.result()
                if r is not None:
                    nfutures.append(executor.submit(add_system_info, r[0], r[1]))
            futures = nfutures

    return len(systems_resp.data)
Esempio n. 13
0
def update_constellations() -> int:
    esi_client: EsiClient = get_esi_client(None, True)
    api: App = get_api()
    consts_request = api.op['get_universe_constellations']()

    consts_resp = esi_client.request(consts_request)
    if consts_resp.status != 200:
        flask.abort(500, 'Could not get constellation ids from ESI')
    futures: List[Future] = []
    with ThreadPoolExecutor(max_workers=500) as executor:
        for const_id in consts_resp.data:
            futures.append(executor.submit(add_constellation_info, const_id, esi_client))
        # re request if it throws an exception
        while len(futures) > 0:
            nfutures: List[Future] = []
            for f in as_completed(futures):
                r: Optional[Tuple[int, EsiClient]] = f.result()
                if r is not None:
                    nfutures.append(executor.submit(add_constellation_info, r[0], r[1]))
            futures = nfutures
    # with waits for all tasks to finish as if .shutdown(True) was called
    return len(consts_resp.data)
Esempio n. 14
0
def send_mail(recipients: List[Dict[str, Any]], body: str,
              subject: str) -> Any:
    api: App = get_api()
    security = EsiSecurity(api, crest_return_url, crest_client_id,
                           crest_client_secret)
    security.update_token({
        'access_token':
        current_user.ssoToken.access_token,
        'expires_in': (current_user.ssoToken.access_token_expires -
                       datetime.utcnow()).total_seconds(),
        'refresh_token':
        current_user.ssoToken.refresh_token
    })

    client = get_esi_client(False)

    mail = {
        "approved_cost": 0,
        "body": body,
        "recipients": recipients,
        "subject": subject
    }
    return client.request(api.op['post_characters_character_id_mail'](
        character_id=current_user.current_char, mail=mail))
Esempio n. 15
0
 def _api(self) -> App:
     if self.__api is None:
         self.__api: App = get_api()
     return self.__api