def get_esi_client(token=None): """ EsiClient is used to call operations for Eve Swagger Interface """ if token: return EsiClient(security=EveClient.get_esi_security(token), headers={'User-Agent': "Krypted Platform"}) else: return EsiClient(headers={'User-Agent': "Krypted Platform"})
def _open(self): """ Initialize EsiPy :return: """ config = key_config.load(self.config_file, self.CONFIG_REQUIREMENTS) self.esi_app = App.create(config['swagger_spec_url']) mc = memcache.Client(['127.0.0.1:11211'], debug=0) cache = MemcachedCache(memcache_client=mc) # init the security object ''' esisecurity = EsiSecurity( app=esiapp, redirect_uri=config.ESI_CALLBACK, client_id=config.ESI_CLIENT_ID, secret_key=config.ESI_SECRET_KEY, ) ''' # init the client self.esi_client = EsiClient( # security=esisecurity, cache=cache, headers={'User-Agent': config['esi_user_agent']})
def do_security(): global client global app print("security: Authenticating") #Retrieve the tokens from the film with open("tokens.txt", "rb") as fp: tokens_file = pickle.load(fp) fp.close() esi_app = EsiApp(cache=cache, cache_time=0, headers=headers) app = esi_app.get_latest_swagger security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers=headers) client = EsiClient(retry_requests=True, headers=headers, security=security) security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': tokens_file['refresh_token'] }) tokens = security.refresh() api_info = security.verify() print("security: Authenticated for " + str(api_info['Scopes']))
def _start(self): self.cache = FileCache(path=self.cache_path) self.esi_app = EsiApp(cache=self.cache, cache_prefix=self.prefix) self.app = self.esi_app.get_latest_swagger self.security = EsiSecurity( app=self.app, redirect_uri='http://localhost/oauth-callback', # This doesnt matter headers={ 'User-Agent': 'Discord bot by Prozn: https://github.com/prozn/dankcord' }, client_id=self.client_id, secret_key=self.secret_key, ) self.esi = EsiClient( retry_requests= False, # set to retry on http 5xx error (default False) headers={ 'User-Agent': 'Discord bot by Prozn: https://github.com/prozn/dankcord' }, security=self.security) self.security.update_token({ 'access_token': '', # leave this empty 'expires_in': -1, # seconds until expiry, so we force refresh anyway 'refresh_token': self.refresh_token }) self.security.refresh()
def __init__(self, token_file): #Retrieve the tokens from the file with open(token_file, "rb") as fp: tokens_file = pickle.load(fp) fp.close() esi_app = EsiApp(cache=cache, cache_time=0, headers=headers) self.app = esi_app.get_latest_swagger self.security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers=headers) self.client = EsiClient(retry_requests=True, headers=headers, security=self.security) self.security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': tokens_file['refresh_token'] }) tokens = self.security.refresh() api_info = self.security.verify() self.character_id = api_info['CharacterID'] self.name = api_info['CharacterName'] #print (str(api_info)) print("security: " + self.name + " authenticated for " + str(api_info['Scopes']))
def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open('test/resources/swagger.json') self.app = App.create('https://esi.tech.ccp.is/latest/swagger.json') self.security = EsiSecurity( app=self.app, redirect_uri=TestEsiPy.CALLBACK_URI, client_id=TestEsiPy.CLIENT_ID, secret_key=TestEsiPy.SECRET_KEY, ) self.cache = DictCache() self.client = EsiClient(self.security, cache=self.cache) self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)
def get_api(fn, scopes): esi_app = App.create( 'https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility') esi_security = EsiSecurity( app=esi_app, redirect_uri='http://localhost:8080/callback', client_id='0b9ac4978a9a4feba20a7eba4f666a46', secret_key='odtDKZWZbwbFnBHNXnOhRX50YrU49owBw1qE3v7p', ) esi_client = EsiClient(retry_requests=True, security=esi_security) def write_refresh_token(refresh_token, **kwargs): with open(fn, "w") as f: f.write(refresh_token) AFTER_TOKEN_REFRESH.add_receiver(write_refresh_token) if os.path.isfile(fn): with open(fn) as f: token = open(fn).read() esi_security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': token }) tokens = esi_security.refresh() else: print(esi_security.get_auth_uri(scopes=scopes)) tokens = esi_security.auth(input()) write_refresh_token(**tokens) api_info = esi_security.verify() return api_info, esi_app, esi_client
def test_esipy_client_no_args(self): client_no_args = EsiClient() self.assertIsNone(client_no_args.security) self.assertTrue(isinstance(client_no_args.cache, DictCache)) self.assertEqual(client_no_args._session.headers['User-Agent'], 'EsiPy/Client - https://github.com/Kyria/EsiPy') self.assertEqual(client_no_args.raw_body_only, False)
def test_esipy_client_with_adapter(self): transport_adapter = HTTPAdapter() client_with_adapters = EsiClient(transport_adapter=transport_adapter) self.assertEqual(client_with_adapters._session.get_adapter('http://'), transport_adapter) self.assertEqual(client_with_adapters._session.get_adapter('https://'), transport_adapter)
def initialize_esi_client(refresh_token=None): """ Retrieves a public or authorized ESI client. Args: auth_id (optional): refresh_token of the user whose client we want to retrieve. By default, a public ESI client is returned. Returns: esi_client (EsiClient): Client object from esipy. """ auth = EsiSecurity( headers={'User-Agent': client_name}, redirect_uri='https://localhost/callback', client_id=client_id, secret_key=secret_key, ) if refresh_token is not None: auth.refresh_token = refresh_token esi_client = EsiClient( auth, retry_requests=True, cache=DictCache(), headers={'User-Agent': client_name}, ) return esi_client
def download_from_esi(killmails): cache = FileCache(path=os.path.join(ROOT_DIR, 'cache/esipy_swagger')) esi_app = EsiApp(cache=cache, cache_time=60 * 60 * 24) app = esi_app.get_latest_swagger client = EsiClient( retry_requests=True, # set to retry on http 5xx error (default False) headers={'User-Agent': 'Something CCP can use to contact you and that define your app'}, raw_body_only=True, # default False, set to True to never parse response and only return raw JSON string content. ) operations = [] for killmail in killmails: operations.append( app.op['get_killmails_killmail_id_killmail_hash']( killmail_hash=killmail['zkb']['hash'], killmail_id=killmail['killmail_id'] ) ) results = client.multi_request(operations) full_killmails = [] for result in results: full_killmails.append(json.loads(result[1].raw)) return full_killmails
def __init__(self, token, refresh=False): self.client_id = os.environ.get('EVE_SKILLS_CID') self.secret_id = os.environ.get('EVE_SKILLS_SECRET') self.redir_url = os.environ.get('EVE_SKILLS_REDIR') self.app = App.create( url= "https://esi.evetech.net/latest/swagger.json?datasource=tranquility" ) self.security = EsiSecurity( app=self.app, redirect_uri=self.redir_url, client_id=self.client_id, secret_key=self.secret_id, ) self.client = EsiClient( header={'User-Agent': 'EVE-SKILLS'}, raw_body_only= False, # parse json automatically, slow, bad performance security=self.security) self.token = None if not refresh: self.token = self.security.auth( token) # use code from login redirect if refresh: print('[I] refreshing token') self.security.update_token({ 'access_token': '', 'expires_in': -1, # force refresh anyway 'refresh_token': token }) self.token = self.security.refresh() print(self.token)
def test_eve_client_call_no_security(self, mock_get_esi_client, mock_esi_request): mock_get_esi_client.return_value = EsiClient( headers={'User-Agent': "Krypted Platform"}) mock_esi_request.return_value = PySwaggerResponse( op='characters_character_id') response = self.eve_client.call('characters_character_id', character_id=634915984) self.assertIsInstance(response, PySwaggerResponse)
def __init__(self, bot): self.bot = bot self.esi = EsiClient( retry_requests=True, headers={ 'User-Agent': f'applucation: MercuryBot contact: {self.bot.config["bot"]["user_agent"]}' })
def test_eve_client_call_required_scopes_corporation_id_with_ceo( self, mock_esi_request, mock_token_refresh, mock_get_esi_client): op = 'corporations_corporation_id_members' mock_esi_request.return_value = PySwaggerResponse(op=op) mock_token_refresh.return_value = True mock_get_esi_client.return_value = EsiClient( headers={'User-Agent': "Krypted Platform"}) response = self.eve_client.call( op, corporation_id=self.eve_corporation_has_ceo.external_id) self.assertIsInstance(response, PySwaggerResponse)
def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open('test/resources/swagger.json') warnings.simplefilter('ignore') self.app = App.create('https://esi.evetech.net/latest/swagger.json') with open(TestEsiPy.RSC_SSO_ENDPOINTS, 'r') as sso_endpoints: with open(TestEsiPy.RSC_JWKS, "r") as jwks: self.security = EsiSecurity( app=self.app, redirect_uri=TestEsiPy.CALLBACK_URI, client_id=TestEsiPy.CLIENT_ID, secret_key=TestEsiPy.SECRET_KEY, sso_endpoints=json.load(sso_endpoints), jwks_key=json.load(jwks)) self.cache = DictCache() self.client = EsiClient(self.security, cache=self.cache) self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)
def test_client_raw_body_only(self): client = EsiClient(raw_body_only=True) self.assertEqual(client.raw_body_only, True) with httmock.HTTMock(public_incursion): incursions = client.request(self.app.op['get_incursions']()) self.assertIsNone(incursions.data) self.assertTrue(len(incursions.raw) > 0) incursions = client.request(self.app.op['get_incursions'](), raw_body_only=False) self.assertIsNotNone(incursions.data)
def init_esi(): esi_app = App.create( 'https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility') esi_security = EsiSecurity( app=esi_app, redirect_uri='https://www.msully.net/stuff/get-token', client_id='fca36d677f9a4b8e8581d8cd2c738c2c', # 'The "Secret Key" should never be human-readable in your application.' secret_key=codecs.decode('AIUr5ntWiEIXiavPjKtUCiNFwlvTBlJqmElgAk4x', 'rot_13'), ) esi_client = EsiClient(esi_security) return ESI(esi_app, esi_security, esi_client)
def __init__(self): self.esi_app = EsiApp() self.app = self.esi_app.get_latest_swagger self.client = EsiClient( retry_requests= True, # set to retry on http 5xx error (default False) headers={ 'User-Agent': 'Something CCP can use to contact you and that define your app' }, raw_body_only= False, # default False, set to True to never parse response and only return raw JSON string content. )
def __init__(self, bot): self.bot = bot self.esi = EsiClient( retry_requests=True, headers={ 'User-Agent': f'application: MercuryBot contact: {self.bot.config["bot"]["user_agent"]}' }, raw_body_only=False, ) self.channels = None self.news_task.start()
def get(release='latest',source='tranquility'): """ Lets try ESIpy instead of bravado... """ global __external_clients__ existing = __external_clients__.get('ESIPY',__mk_key__(release,source)) if existing is None: existing = EsiClient( retry_requests=True, # set to retry on http 5xx error (default False) header={'User-Agent': 'Jimmy - api test app: [email protected] @grux on slack'}, raw_body_only=True, # default False, set to True to never parse response and only return raw JSON string content. ) __external_clients__.set('ESIPY',__mk_key__(release,source),existing) return existing
def get_esi_client_for_account(token: Optional[SSOToken], noauth: bool = False, retry_request: bool = False) -> EsiClient: if noauth: return EsiClient(timeout=20, headers={'User-Agent': config.user_agent}, cache=DummyCache(), retry_requests=retry_request) signal: Signal = Signal() signal.add_receiver(SSOToken.update_token_callback) security = EsiSecurity(crest_return_url, crest_client_id, crest_client_secret, headers={'User-Agent': config.user_agent}, signal_token_updated=signal, token_identifier=token.tokenID) security.update_token(token.info_for_esi_security()) return EsiClient(security, timeout=20, headers={'User-Agent': config.user_agent}, cache=DummyCache(), retry_requests=retry_request)
def main(configpath="."): global sc, swagger, esi config.read("%s/config.ini" % configpath) searches.read("%s/searches.ini" % configpath) sc = SlackClient(config.get('slack', 'slack_api_token')) swagger = App.create(url="https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility") esi = EsiClient( retry_requests=True, # set to retry on http 5xx error (default False) header={'User-Agent': 'Killmail Slack Bot by Prozn https://github.com/prozn/dankbot/'} ) while True: if getRedisq(): time.sleep(0.5) else: time.sleep(5)
def __init__(self, bot): self.bot = bot self.TYPE_MODELS = { 'region': TheraEveRegion, 'system': TheraEveSystem, 'constellation': TheraEveConstellation } self.last_thera = None self.channels = None self.esi = EsiClient( retry_requests=True, headers={ 'User-Agent': f'application: MercuryBot contact: {self.bot.config["bot"]["user_agent"]}' }, raw_body_only=False) self.thera.start()
def authenticate(): app = App.create( url="https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility" ) security = EsiSecurity( app=app, redirect_uri='http://localhost:51350', client_id=secret['client_id'], secret_key=secret['secret_key'], ) client = EsiClient(retry_requests=True, header={'User-Agent': 'shipLocation'}, security=security) eve_sso_auth_url = security.get_auth_uri( scopes=['esi-location.read_ship_type.v1']) webbrowser.open(eve_sso_auth_url, new=2) # open in a new browser tab auth_code = fetch_auth_code( ) # fetch authentication code using a temporary web server tokens = security.auth(auth_code) return (app, client, security, tokens)
def _load_esi(): loaded = False count = 0 while not loaded: if count < MAX_RETRY: count += 1 try: esi_app = EsiApp().get_latest_swagger esi_client = EsiClient(retry_requests=True, headers={'User-Agent': USER_AGENT}, raw_body_only=True) loaded = True return esi_app, esi_client except HTTPError: logger.warning('Loading swagger failed ' + str(count) + '/' + str(MAX_RETRY) + ', retrying...') time.sleep(0.5) pass else: raise ConnectionError( 'Error loading swagger. Please restart the bot.')
def do_security(tokens_file, scopes): esi_app = EsiApp(cache=cache, cache_time=0) app = esi_app.get_latest_swagger security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers=headers) client = EsiClient(retry_requests=True, headers=headers, security=security) print("Open link in browser and authorize") print(security.get_auth_uri(scopes=scopes)) code = input("Enter in code:\n") tokens = security.auth(code) print(tokens) print("\n Writing tokens to " + str(tokens_file)) with open(tokens_file, 'wb') as fp: pickle.dump(tokens, fp) fp.close()
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)) # 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
def setup_esi(app_id, app_secret, refresh_token, cache=DictCache()): """Set up the ESI client Args: app_id (string): SSO Application ID from CCP app_secret (string): SSO Application Secret from CCP refresh_token (string): SSO refresh token cache (False, optional): esipy.cache instance Returns: tuple: esi app definition, esi client >>> setup_esi(CONFIG['SSO_APP_ID'], CONFIG['SSO_APP_KEY'], ... CONFIG['SSO_REFRESH_TOKEN'], cache) # doctest: +ELLIPSIS (<pyswagger.core.App object ...>, <esipy.client.EsiClient object ...>) """ esi_meta = EsiApp(cache=cache) esi = esi_meta.get_latest_swagger esi_security = EsiSecurity( redirect_uri='http://localhost', client_id=app_id, secret_key=app_secret, headers={'User-Agent': 'https://github.com/eve-n0rman/structurebot'}) esi_security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': refresh_token }) esi_client = EsiClient( retry_requests=True, headers={'User-Agent': 'https://github.com/eve-n0rman/structurebot'}, raw_body_only=False, security=esi_security, cache=cache) return (esi, esi_client, esi_security)
def __init__(self): self.db = Database() self.config = Config() self.scopes = self.config.getConfig()["settings"]["esiScopes"] self.esi_app = App.create( url=self.config.getConfig()["settings"]["esiURL"], ) self.security = EsiSecurity( app=self.esi_app, redirect_uri=self.config.getConfig()["settings"]["esiCallback"], client_id=self.config.getConfig()["settings"]["esiClientID"], secret_key=self.config.getConfig()["settings"]["esiSecretKey"], headers={ 'User-Agent': self.config.getConfig()["settings"]["esiCustomHeader"] }) self.client = EsiClient( security=self.security, retry_requests=True, headers={ 'User-Agent': self.config.getConfig()["settings"]["esiCustomHeader"] })