preston-async 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
preston/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .preston import Preston # noqa
2
+
3
+
4
+ __author__ = "Matt Boulanger"
5
+ __email__ = "mattboulanger@fastmail.com"
6
+ __license__ = "MIT"
preston/cache.py ADDED
@@ -0,0 +1,117 @@
1
+ from datetime import datetime, UTC
2
+ import math
3
+ import time
4
+ from typing import Optional
5
+
6
+
7
+ class Cache:
8
+ def __init__(self):
9
+ """Cache class.
10
+
11
+ The cache is designed to respect the caching rules of ESI as to
12
+ not request a page more often than it is updated by the server.
13
+
14
+ Args:
15
+ None
16
+
17
+ Returns:
18
+ None
19
+ """
20
+ self.data: dict = {}
21
+
22
+ def _get_expiration(self, headers: dict) -> int:
23
+ """Gets the expiration time of the data from the response headers.
24
+
25
+ Args:
26
+ headers: dictionary of headers from ESI
27
+
28
+ Returns:
29
+ value of seconds from now the data expires
30
+ """
31
+ expiration_str = headers.get("expires")
32
+ if not expiration_str:
33
+ return 0
34
+ expiration = datetime.strptime(
35
+ expiration_str, "%a, %d %b %Y %H:%M:%S %Z"
36
+ ).replace(tzinfo=UTC)
37
+ delta = (expiration - datetime.now(UTC)).total_seconds()
38
+ return math.ceil(abs(delta))
39
+
40
+ def set(self, data: dict, headers: dict, url: str) -> None:
41
+ """Adds a response to the cache.
42
+
43
+ Args:
44
+ data: response from ESI
45
+ headers: headers from ESI
46
+ url: url for the request
47
+
48
+ Returns:
49
+ None
50
+ """
51
+ self.data[url] = SavedEndpoint(data, self._get_expiration(headers))
52
+
53
+ def _check_expiration(self, url: str, data: "SavedEndpoint") -> "SavedEndpoint":
54
+ """Checks the expiration time for data for a url.
55
+
56
+ If the data has expired, it is deleted from the cache.
57
+
58
+ Args:
59
+ url: url to check
60
+ data: page of data for that url
61
+
62
+ Returns:
63
+ value of either the passed data or None if it expired
64
+ """
65
+ if data.expires_after < time.time():
66
+ del self.data[url]
67
+ data = None
68
+ return data
69
+
70
+ def check(self, url: str) -> Optional[dict]:
71
+ """Check if data for a url has expired.
72
+
73
+ Data is not fetched again if it has expired.
74
+
75
+ Args:
76
+ url: url to check expiration on
77
+
78
+ Returns:
79
+ value of the data, possibly None
80
+ """
81
+ data = self.data.get(url)
82
+ if data:
83
+ data = self._check_expiration(url, data)
84
+ return data.data if data else None
85
+
86
+ def __len__(self) -> int:
87
+ """Returns the number of items in the stored data.
88
+
89
+ More of a debugging tool, since getting the number of dictionary keys
90
+ isn't a good indicator of how much data is actually here.
91
+
92
+ Args:
93
+ None
94
+
95
+ Returns:
96
+ value of the number of keys in the data
97
+ """
98
+ return len(self.data.keys())
99
+
100
+
101
+ class SavedEndpoint:
102
+ def __init__(self, data: dict, expires_in: float) -> None:
103
+ """SavedEndpoint class.
104
+
105
+ A wrapper around a page from ESI that also includes the expiration time
106
+ in seconds and the time after which the wrapped data expires.
107
+
108
+ Args:
109
+ data: page data from ESI
110
+ expires_in: number of seconds from now that the data expires
111
+
112
+ Returns:
113
+ None
114
+ """
115
+ self.data = data
116
+ self.expires_in = expires_in
117
+ self.expires_after = time.time() + expires_in
preston/preston.py ADDED
@@ -0,0 +1,604 @@
1
+ import base64
2
+ import re
3
+ import time
4
+ from http import HTTPStatus
5
+ from json import JSONDecodeError
6
+ from typing import Optional, Any, Union, Coroutine
7
+
8
+ import jwt
9
+ import asyncio
10
+ import aiohttp
11
+
12
+ from .cache import Cache
13
+
14
+
15
+ class Preston:
16
+ """Preston class.
17
+
18
+ This class is used to interface with the EVE Online "ESI" API.
19
+
20
+ The __init__ method only **kwargs instead of a specific
21
+ listing of arguments; here's the list of useful key-values:
22
+
23
+ version version of the spec to load
24
+
25
+ user_agent user-agent to use
26
+
27
+ client_id app's client id
28
+
29
+ client_secret app's client secret
30
+
31
+ callback_url app's callback url
32
+
33
+ scope app's scope(s)
34
+
35
+ access_token if supplied along with access_expiration,
36
+ Preston will make authenticated calls to ESI
37
+
38
+ access_expiration see above
39
+
40
+ refresh_token if supplied, Preston will use it to get new
41
+ access tokens; can be supplied with or without
42
+ access_token and access_expiration
43
+
44
+ Args:
45
+ kwargs: various configuration options
46
+ """
47
+
48
+ BASE_URL = "https://esi.evetech.net"
49
+ SPEC_URL = BASE_URL + "/_{}/swagger.json"
50
+ ISSUER = "https://login.eveonline.com"
51
+ OAUTH_URL = ISSUER + "/v2/oauth"
52
+ JWKS_URL = ISSUER + "/oauth/jwks"
53
+ TOKEN_URL = OAUTH_URL + "/token"
54
+ AUTHORIZE_URL = OAUTH_URL + "/authorize"
55
+ METHODS = ["get", "post", "put", "delete"]
56
+ OPERATION_ID_KEY = "operationId"
57
+ VAR_REPLACE_REGEX = r"{(\w+)}"
58
+
59
+ def __init__(self, **kwargs: Any):
60
+ self.cache = Cache()
61
+ self.spec = None
62
+ self.version = kwargs.get("version", "latest")
63
+ self.timeout = kwargs.get("timeout", 6)
64
+ self.retries = kwargs.get("retries", 4)
65
+ self.client_id = kwargs.get("client_id")
66
+ self.client_secret = kwargs.get("client_secret")
67
+ self.callback_url = kwargs.get("callback_url")
68
+
69
+ # Allow scopes to be directly pasted from developers.eveonline.com no matter if it is one or multiple
70
+ scope = kwargs.get("scope", "")
71
+ if isinstance(scope, str):
72
+ self.scope = scope
73
+ elif isinstance(scope, list):
74
+ self.scope = " ".join(scope)
75
+ else:
76
+ raise TypeError("scope must be a string or list!")
77
+
78
+ self.access_token = kwargs.get("access_token")
79
+ self.access_expiration = kwargs.get("access_expiration")
80
+ self.refresh_token = kwargs.get("refresh_token")
81
+ self.refresh_token_callback = kwargs.get("refresh_token_callback")
82
+ self.stored_headers = []
83
+ self._kwargs = kwargs
84
+ self.session = None
85
+
86
+ async def _make_session(self):
87
+ """Async portion of initialization, to be called first in async functions"""
88
+
89
+ if self.session is None:
90
+ self.session = aiohttp.ClientSession()
91
+ self.session.headers.update(
92
+ {"User-Agent": self._kwargs.get("user_agent", ""), "Accept": "application/json"}
93
+ )
94
+
95
+ async def _close(self):
96
+ if not self.session.closed:
97
+ await self.session.close()
98
+
99
+ def __del__(self):
100
+ try:
101
+ if not self.session.closed:
102
+ loop = asyncio.get_event_loop()
103
+ if loop.is_running():
104
+ asyncio.ensure_future(self._close())
105
+ else:
106
+ loop.run_until_complete(self._close())
107
+ except (AttributeError, RuntimeError):
108
+ # No session yet, or no event loop left to close it on (e.g. interpreter shutdown)
109
+ pass
110
+
111
+ async def _retry_request(
112
+ self,
113
+ requests_function: callable,
114
+ target_url: str,
115
+ return_metadata=False,
116
+ **kwargs,
117
+ ) -> Coroutine:
118
+ """
119
+
120
+ Tries some request with exponential backoff on server-side failures.
121
+ And immediately raises client-side failures.
122
+ This automatically adds a timeout to the request as well.
123
+
124
+ Args:
125
+ requests_function: Function to call to make the request
126
+ target_url: Target URL for request
127
+ return_metadata: Whether to return raw response or json. In this case no retries on JSONDecodeError
128
+ **kwargs: Additional keyword arguments for function
129
+ Returns:
130
+ new response
131
+ Raises:
132
+ aiohttp.ClientResponseError (for client-side errors)
133
+ aiohttp.ClientConnectionError (for connection errors)
134
+ """
135
+
136
+ for x in range(self.retries):
137
+ try:
138
+ async with requests_function(target_url, **kwargs, timeout=self.timeout) as resp:
139
+ resp.raise_for_status()
140
+ if await resp.text():
141
+ json_data = await resp.json()
142
+ else:
143
+ json_data = None
144
+
145
+ if return_metadata:
146
+ return json_data, resp.headers, resp.url
147
+ return json_data
148
+
149
+ except TimeoutError:
150
+ pass # Just try again
151
+
152
+ except JSONDecodeError:
153
+ pass # Message was not completed. Just try again
154
+
155
+ except aiohttp.ClientPayloadError:
156
+ pass # Message was not completed. Just try again
157
+
158
+ except aiohttp.ClientResponseError as exc:
159
+ code = exc.status
160
+ if code in [
161
+ HTTPStatus.TOO_MANY_REQUESTS,
162
+ 420, # Enhance your calm, ESI Error limit
163
+ ]:
164
+ await asyncio.sleep(int(exc.headers.get("X-Esi-Error-Limit-Reset", 0)))
165
+ elif code not in [
166
+ HTTPStatus.INTERNAL_SERVER_ERROR,
167
+ HTTPStatus.BAD_GATEWAY,
168
+ HTTPStatus.SERVICE_UNAVAILABLE,
169
+ HTTPStatus.GATEWAY_TIMEOUT,
170
+ ]:
171
+ raise
172
+
173
+ except aiohttp.ClientConnectionError:
174
+ raise # No internet, raise immediately without retry
175
+
176
+ # Exponential Backoff
177
+ await asyncio.sleep(2 ** x)
178
+
179
+ raise aiohttp.ClientConnectionError("ESI could not complete the request.")
180
+
181
+ def copy(self) -> "Preston":
182
+ """Creates a copy of this Preston object.
183
+
184
+ The returned instance is not connected to this, so you can set
185
+ whichever headers or other data you want without impacting this instance.
186
+
187
+ The configuration of the returned instance will match the (original)
188
+ configuration of this instance - the kwargs are reused.
189
+
190
+ Args:
191
+ None
192
+
193
+ Returns:
194
+ new Preston instance
195
+ """
196
+ return Preston(**self._kwargs)
197
+
198
+ def _get_authorization_headers(self) -> dict:
199
+ """Constructs and returns the Authorization header for the client app.
200
+
201
+ Args:
202
+ None
203
+
204
+ Returns:
205
+ header dict for communicating with the authorization endpoints
206
+ """
207
+ auth = base64.encodebytes(
208
+ bytes(f"{self.client_id}:{self.client_secret}", "latin-1")
209
+ ).decode("latin-1")
210
+ auth = auth.replace("\n", "").replace(" ", "")
211
+ auth = "Basic {}".format(auth)
212
+ headers = {"Authorization": auth}
213
+ return headers
214
+
215
+ async def _try_refresh_access_token(self):
216
+ """Attempts to get a new access token using the refresh token, if needed.
217
+
218
+ If the access token is expired and this instance has a stored refresh token,
219
+ then the refresh token is in the API call to get a new access token. If
220
+ successful, this instance is modified in-place with that new access token.
221
+
222
+ Also updates the `requests` session with the new header.
223
+
224
+ Args:
225
+ None
226
+
227
+ Returns:
228
+ None
229
+ """
230
+ await self._make_session()
231
+
232
+ if self.refresh_token:
233
+ if not self.access_token or self._is_access_token_expired():
234
+ headers = {
235
+ "Content-Type": "application/x-www-form-urlencoded",
236
+ }
237
+
238
+ data = {
239
+ "grant_type": "refresh_token",
240
+ "refresh_token": self.refresh_token,
241
+ "client_id": self.client_id,
242
+ }
243
+
244
+ response_data = await self._retry_request(
245
+ self.session.post,
246
+ self.TOKEN_URL,
247
+ headers=headers,
248
+ data=data,
249
+ )
250
+
251
+ self.access_token = response_data["access_token"]
252
+ self.access_expiration = time.time() + response_data["expires_in"]
253
+ self.refresh_token = response_data.get(
254
+ "refresh_token", self.refresh_token
255
+ )
256
+ if self.refresh_token_callback is not None:
257
+ await self.refresh_token_callback(self)
258
+
259
+ if self.access_token:
260
+ self.session.headers.update(
261
+ {"Authorization": f"Bearer {self.access_token}"}
262
+ )
263
+
264
+ def _is_access_token_expired(self) -> bool:
265
+ """Returns true if the stored access token has expired.
266
+
267
+ Args:
268
+ None
269
+
270
+ Returns:
271
+ True if the access token is expired
272
+ """
273
+ return time.time() > self.access_expiration
274
+
275
+ def get_authorize_url(self, state: str = "default") -> str:
276
+ """Constructs and returns the authorization URL.
277
+
278
+ This is the URL that a user will have to navigate to in their browser
279
+ and complete the login and authorization flow. Upon completion, they
280
+ will be redirected to your app's callback URL.
281
+
282
+ Args:
283
+ state: state of the application
284
+
285
+ Returns:
286
+ URL
287
+ """
288
+ return (
289
+ f"{self.AUTHORIZE_URL}?response_type=code&redirect_uri={self.callback_url}"
290
+ f"&client_id={self.client_id}&scope={self.scope.replace(' ', '%20')}&state={state}"
291
+ )
292
+
293
+ async def authenticate(self, code: str) -> "Preston":
294
+ """Authenticates using the code from the EVE SSO.
295
+
296
+ A new Preston object is returned; this object is not modified.
297
+
298
+ The intended usage is:
299
+
300
+ auth = preston.authenticate('some_code_here')
301
+
302
+ Args:
303
+ code: SSO code
304
+
305
+ Returns:
306
+ new Preston, authenticated
307
+ """
308
+ headers = {
309
+ "Content-Type": "application/x-www-form-urlencoded",
310
+ }
311
+
312
+ data = {
313
+ "grant_type": "authorization_code",
314
+ "code": code,
315
+ "redirect_uri": self.callback_url,
316
+ "client_id": self.client_id,
317
+ }
318
+
319
+ await self._make_session()
320
+ response_data = await self._retry_request(
321
+ self.session.post,
322
+ self.TOKEN_URL,
323
+ headers=headers,
324
+ data=data,
325
+ )
326
+
327
+ new_kwargs = dict(self._kwargs)
328
+ new_kwargs["access_token"] = response_data["access_token"]
329
+ new_kwargs["access_expiration"] = time.time() + float(
330
+ response_data["expires_in"]
331
+ )
332
+ new_kwargs["refresh_token"] = response_data["refresh_token"]
333
+
334
+ return Preston(**new_kwargs)
335
+
336
+ async def authenticate_from_token(self, refresh_token) -> "Preston":
337
+ """Authenticates usign a stored refresh token.
338
+
339
+ A new Preston object is returned; this object is not modified.
340
+
341
+ The intended usage is:
342
+
343
+ auth = preston.authenticate('refresh_token')
344
+
345
+ Args:
346
+ refresh_token: currently active refresh token
347
+
348
+ Returns:
349
+ new Preston, authenticated
350
+ """
351
+ if len(refresh_token) != 24:
352
+ raise Exception(
353
+ "You have passed in a legacy token, these are no longer supported by CCP!"
354
+ )
355
+
356
+ new_kwargs = dict(self._kwargs)
357
+ new_kwargs["refresh_token"] = refresh_token
358
+ new_kwargs["access_token"] = None
359
+ return Preston(**new_kwargs)
360
+
361
+ async def _get_spec(self) -> dict:
362
+ """Fetches the OpenAPI spec from the server.
363
+
364
+ If the spec has already been fetched, the cached version is returned instead.
365
+
366
+ Args:
367
+ None
368
+
369
+ Returns:
370
+ OpenAPI spec data
371
+ """
372
+ if self.spec:
373
+ return self.spec
374
+
375
+ await self._make_session()
376
+ self.spec = await self._retry_request(
377
+ self.session.get, self.SPEC_URL.format(self.version)
378
+ )
379
+ return self.spec
380
+
381
+ async def _get_path_for_op_id(self, op_id: str) -> Optional[str]:
382
+ """Searches the spec for a path matching the operation id.
383
+
384
+ Args:
385
+ op_id: operation id
386
+
387
+ Returns:
388
+ path to the endpoint, or `None` if not found
389
+ """
390
+ spec = await self._get_spec()
391
+ for path_key, path_value in spec["paths"].items():
392
+ for method in self.METHODS:
393
+ if method in path_value:
394
+ if self.OPERATION_ID_KEY in path_value[method]:
395
+ if path_value[method][self.OPERATION_ID_KEY] == op_id:
396
+ return path_key
397
+ return None
398
+
399
+ def _insert_vars(self, path: str, data: dict) -> tuple[str, dict]:
400
+ """Inserts variables into the ESI URL path.
401
+
402
+ Args:
403
+ path: raw ESI URL path
404
+ data: data to insert into the URL
405
+
406
+ Returns:
407
+ tuple of the path with variables filled, and
408
+ and remaining, unused dict items
409
+ """
410
+ data = data.copy()
411
+ while True:
412
+ match = re.search(self.VAR_REPLACE_REGEX, path)
413
+ if not match:
414
+ return path, data
415
+ replace_from = match.group(0)
416
+ replace_with = str(data.pop(match.group(1), ""))
417
+ path = path.replace(replace_from, replace_with)
418
+
419
+ def _build_url(self, path: str, data: dict) -> str:
420
+ """Build a complete URL.
421
+
422
+ Args:
423
+ path: raw ESI URL path
424
+ data: data to insert into the URL
425
+
426
+ Returns:
427
+ url
428
+ """
429
+ path, query_params = self._insert_vars(path, data)
430
+ target_url = f"{self.BASE_URL}{path}"
431
+
432
+ return target_url
433
+
434
+ async def whoami(self) -> dict:
435
+ """Returns the basic information about the authenticated character.
436
+
437
+ Obviously doesn't do anything if this Preston instance is not
438
+ authenticated, so it returns an empty dict.
439
+
440
+ Args:
441
+ None
442
+
443
+ Returns:
444
+ character info if authenticated, otherwise an empty dict
445
+ """
446
+
447
+ await self._try_refresh_access_token()
448
+
449
+ if not self.access_token:
450
+ return {}
451
+
452
+ try:
453
+ # Get the JWT header to determine the key ID (kid)
454
+ unverified_header = jwt.get_unverified_header(self.access_token)
455
+
456
+ # Fetch the public keys (JWKS)
457
+ async with self.session.get(self.JWKS_URL) as jwks_response:
458
+ jwks = await jwks_response.json()
459
+
460
+ # Find the public key with matching kid
461
+ key = next(
462
+ (k for k in jwks["keys"] if k["kid"] == unverified_header["kid"]), None
463
+ )
464
+ if not key:
465
+ raise Exception("Unable to find appropriate public key for JWT.")
466
+
467
+ # Convert JWKS to RSA public key
468
+ public_key = jwt.algorithms.RSAAlgorithm.from_jwk(key)
469
+
470
+ # Decode and validate JWT
471
+ payload = jwt.decode(
472
+ self.access_token,
473
+ public_key,
474
+ algorithms=["RS256"],
475
+ audience=self.client_id,
476
+ issuer=self.ISSUER,
477
+ leeway=10, # allow 10 seconds of clock skew
478
+ )
479
+
480
+ return {
481
+ "character_id": payload.get("sub").split(":")[-1],
482
+ "character_name": payload.get("name"),
483
+ "scopes": payload.get("scp", []),
484
+ "owner_hash": payload.get("owner"),
485
+ "token_type": payload.get("token_type", "Character"),
486
+ }
487
+
488
+ except Exception as e:
489
+ print(f"[whoami] Failed to decode/verify JWT: {e}")
490
+ return {}
491
+
492
+ async def get_path(self, path: str, data: dict) -> dict:
493
+ """Queries the ESI by an endpoint URL.
494
+
495
+ This method is not marked "private" as it _can_ be used
496
+ by consuming code, but it's probably easier to call the
497
+ `get_op` method instead.
498
+
499
+ Args:
500
+ path: raw ESI URL path
501
+ data: data to insert into the URL
502
+
503
+ Returns:
504
+ ESI data
505
+ """
506
+ target_url = self._build_url(path, data)
507
+
508
+ cached_data = self.cache.check(target_url)
509
+ if cached_data:
510
+ return cached_data
511
+ await self._try_refresh_access_token()
512
+
513
+ data, headers, url = await self._retry_request(
514
+ self.session.get, target_url, return_metadata=True
515
+ )
516
+ self.cache.set(data, headers, url)
517
+ self.stored_headers.insert(0, headers)
518
+ return data
519
+
520
+ async def get_op(self, op_id: str, **kwargs: str) -> dict:
521
+ """Queries the ESI by looking up an operation id.
522
+
523
+ Endpoints are cached, so calls to this method for the
524
+ same op and args will return the data from the cache
525
+ instead of making the API call.
526
+
527
+ Passed kwargs will first supply parameters in the URL,
528
+ and then unused items will be used as query params.
529
+
530
+ Args:
531
+ op_id: operation id
532
+ kwargs: data to populate the endpoint's URL variables
533
+
534
+ Returns:
535
+ ESI data
536
+ """
537
+ path = await self._get_path_for_op_id(op_id)
538
+ return await self.get_path(path, kwargs)
539
+
540
+ async def post_path(
541
+ self, path: str, path_data: Union[dict, None], post_data: Any
542
+ ) -> dict:
543
+ """Modifies the ESI by an endpoint URL.
544
+
545
+ This method is not marked "private" as it _can_ be used
546
+ by consuming code, but it's probably easier to call the
547
+ `get_op` method instead.
548
+
549
+ Args:
550
+ path: raw ESI URL path
551
+ path_data: data to format the path with (can be None)
552
+ post_data: data to send to ESI
553
+
554
+ Returns:
555
+ ESI data
556
+ """
557
+ target_url = self._build_url(path, path_data)
558
+ await self._try_refresh_access_token()
559
+ return await self._retry_request(self.session.post, target_url, json=post_data)
560
+
561
+ async def post_op(self, op_id: str, path_data: Union[dict, None], post_data: Any) -> dict:
562
+ """Modifies the ESI by looking up an operation id.
563
+
564
+ Args:
565
+ op_id: operation id
566
+ path_data: data to format the path with (can be None)
567
+ post_data: data to send to ESI
568
+
569
+ Returns:
570
+ ESI data
571
+ """
572
+ path = await self._get_path_for_op_id(op_id)
573
+ return await self.post_path(path, path_data, post_data)
574
+
575
+ async def delete_path(self, path: str, path_data: Union[dict, None]) -> dict:
576
+ """Deletes a resource in the ESI by an endpoint URL.
577
+
578
+ This method is not marked "private" as it _can_ be used
579
+ by consuming code, but it's probably easier to call the
580
+ `delete_op` method instead.
581
+
582
+ Args:
583
+ path: raw ESI URL path
584
+ path_data: data to format the path with (can be None)
585
+
586
+ Returns:
587
+ ESI response data
588
+ """
589
+ target_url = self._build_url(path, path_data)
590
+ await self._try_refresh_access_token()
591
+ return await self._retry_request(self.session.delete, target_url)
592
+
593
+ async def delete_op(self, op_id: str, path_data: Union[dict, None]) -> dict:
594
+ """Deletes a resource in the ESI by looking up an operation id.
595
+
596
+ Args:
597
+ op_id: operation id
598
+ path_data: data to format the path with (can be None)
599
+
600
+ Returns:
601
+ ESI response data
602
+ """
603
+ path = await self._get_path_for_op_id(op_id)
604
+ return await self.delete_path(path, path_data)
@@ -0,0 +1,244 @@
1
+ Metadata-Version: 2.5
2
+ Name: preston-async
3
+ Version: 5.0.0
4
+ Summary: Async (asyncio/aiohttp) EVE ESI API access tool, forked from Preston
5
+ Project-URL: homepage, https://github.com/14rynx/Preston
6
+ Project-URL: repository, https://github.com/14rynx/Preston
7
+ Project-URL: upstream, https://github.com/Celeo/Preston
8
+ Author-email: Celeo <mattboulanger@fastmail.com>
9
+ Maintainer-email: 14rynx <laynx.austrene@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: aiohttp,asyncio,esi,eve,eve online
13
+ Classifier: Environment :: Console
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Framework :: aiohttp
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: aiohttp<4,>=3.9
22
+ Requires-Dist: pyjwt[crypto]<3,>=2.8
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Preston (async)
26
+
27
+ [![CI](https://github.com/14rynx/Preston/actions/workflows/ci.yml/badge.svg)](https://github.com/14rynx/Preston/actions/workflows/ci.yml)
28
+ [![PyPI](https://img.shields.io/pypi/v/preston-async)](https://pypi.org/project/preston-async/)
29
+ [![Python version](https://img.shields.io/badge/Python-3.11+-blue)](https://www.python.org/)
30
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
31
+ [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
32
+
33
+ Preston is a Python library for accessing EVE Online's ESI API.
34
+
35
+ This is an asyncio/aiohttp fork of [Celeo/Preston](https://github.com/Celeo/Preston), published as `preston-async`.
36
+ It is still imported as `preston`, so don't install it alongside the original `preston` package.
37
+ All methods that talk to ESI are coroutines and must be awaited, and `refresh_token_callback` must be an `async` function.
38
+
39
+ ## Quick links
40
+
41
+ * EVE ESI: <https://esi.evetech.net>
42
+ * EVE developers: <https://developers.eveonline.com>
43
+
44
+ ## Installation
45
+
46
+ From [pip](https://pip.pypa.io/en/stable/):
47
+
48
+ ```sh
49
+ pip install preston-async
50
+ ```
51
+
52
+ ## Initialization
53
+
54
+ ```python
55
+ from preston import Preston
56
+
57
+ preston = Preston()
58
+ ```
59
+
60
+ There are values that you can pass to `__init__` as kwargs; those are detailed in the docstring for the class.
61
+
62
+ ## Usage
63
+
64
+ There are 3 main things that Preston does:
65
+
66
+ 1. Unauthenticated calls to ESI
67
+ 2. User authentication
68
+ 3. Authenticated calls to ESI for that user
69
+
70
+ For #1, all you need to do is initialize a Preston object and make the call:
71
+
72
+ ```python
73
+ preston = Preston(
74
+ user_agent='some_user_agent'
75
+ )
76
+
77
+ data = await preston.get_op('get_characters_character_id', character_id=91316135)
78
+ # ...
79
+ ```
80
+
81
+ You should always include a good `user_agent`.
82
+
83
+ Additionally, a `post_op` method exists, that takes a dictionary (instead of **kwargs) and another parameter; the former is used like above, to satisfy the URL parameters, and the latter is sent to the ESI endpoint as the payload.
84
+
85
+ For #2, there are 2 methods that you'll need, `get_authorize_url` and `authenticate`, and several `__init__` kwargs.
86
+
87
+ ```python
88
+ preston = Preston(
89
+ user_agent='some_user_agent',
90
+ client_id='something',
91
+ client_secret='something',
92
+ callback_url='something',
93
+ scope='maybe_something',
94
+ )
95
+ ```
96
+
97
+ You can find the last 4 values in your application on the [EVE Dev site](https://developers.eveonline.com/).
98
+
99
+ When you have a Preston instance constructed like this, you can make the call to `get_authorize_url`:
100
+
101
+ ```python
102
+ preston.get_authorize_url()
103
+ # https://login.eveonline.com/oauth/...
104
+ ```
105
+
106
+ This is the URL that your user needs to visit and complete the flow. They'll be redirected to your app's callback URL, so you have to be monitoring that.
107
+
108
+ > [!NOTE]
109
+ > `get_authorize_url()` takes an optional argument 'state' that you can use to make sure you get the code back from the right user.
110
+ > If you do not set this then the url includes `?state=default`
111
+
112
+ When you get their callback, take the code paramter from the URL and pass it to `authenticate`:
113
+
114
+ ```python
115
+ auth = await preston.authenticate('their_code_here')
116
+ ```
117
+
118
+ > [!NOTE]
119
+ > The return variable and it's reassignment: this method returns a *new* instance, with the corresponding variables and headers setup for authenticated ESI calls.
120
+
121
+ Finally for #3, having followed the steps above, you just make calls like previously, but you can do so to the authenticated-only endpoints. Make sure that if you're calling
122
+ an endpoint that requires a specific scope, your app on EVE Devs has that scoped added and you've supplied it to the Preston initialization.
123
+
124
+ ### Resuming authentication
125
+
126
+ If your app uses scopes, it'll receive a `refresh_token` alongside the `access_token`. The access token, per usual, only lasts 20 minutes before it expires. In this situation,
127
+ the refresh token can be used to get a *new* access token and a *new* refresh token. If your Preston instance has a refresh token, this will be done automatically when the access token expires.
128
+
129
+ If you want to store your current refresh token so you can fetch data with authorization later on again, you can do that with preston as following.
130
+
131
+ To get the current refresh token and keep getting informed when it changes, initialize Preston with a refresh token callback function.
132
+ This function should look something like this:
133
+
134
+ ```python
135
+ async def my_refresh_token_callback(preston: Preston):
136
+ # To figure out which user called the callback, you can use the whoami() function.
137
+ current_user_info = await preston.whoami()
138
+ character_id = current_user_info.get("character_id")
139
+ scopes = current_user_info.get("scopes")
140
+
141
+ # Now you probably want store the refresh token somewhere e.g. your db
142
+ # Or something else persistent. In the simple case all users have the same scopes
143
+ # and you are using a python shelve, you would do something like this:
144
+ python_shelve[character_id] = preston.refresh_token
145
+ ```
146
+
147
+ You can pass this function to Preston on initialization:
148
+
149
+ ```python
150
+ preston = Preston(
151
+ ...,
152
+ refresh_token_callback=my_refresh_token_callback
153
+ )
154
+ ```
155
+
156
+ Now every time Preston needs to get new tokens, it will also call your function so you can stay up to date.
157
+
158
+ If you want to resume authentication, you can use the refresh token on initialization:
159
+
160
+ ```python
161
+ preston = Preston(
162
+ ...,
163
+ refresh_token='your_refresh_token_here'
164
+ )
165
+ ```
166
+ Or you can get an authorized Preston instance from an unauthorized:
167
+
168
+ ```python
169
+ auth = await preston.authenticate_from_token('your_refresh_token_here')
170
+ ```
171
+
172
+ > [!NOTE]
173
+ > You can also pass the `access_token` to a new Preston instance, but there's less of a use case for that, as either you have an app with scopes, yielding a refresh token,
174
+ > or an authentication-only app where you only use the access token to verify identity and some basic information before moving on.
175
+
176
+ ## Error Handling
177
+
178
+ Preston usually retries network-related exceptions up to 4 times with exponential backoff (1, 2, 4, 8, ... seconds), and times out any single request
179
+ after 6 seconds. This means that at most any single call can take 39 seconds. You can modify this behaviour with optional arguments:
180
+ ```python
181
+ preston = Preston(
182
+ timeout="timeout_per_request_in_seconds",
183
+ retrues="max_number_of_retries",
184
+ )
185
+ ```
186
+
187
+ For non network related issues, Preston raises the exceptions generated by aiohttp immediately.
188
+ You can find all possible errors [here](https://docs.aiohttp.org/en/stable/client_reference.html#client-exceptions).
189
+
190
+ A simple error handling scheme might look something like this:
191
+
192
+ ```python
193
+ try:
194
+ authed_preston = await preston.authenticate_from_token(character.token)
195
+ except aiohttp.ClientResponseError as exp:
196
+ # Some kind of error the user has to deal with e.g. no permissions, token revoked on website
197
+ ...
198
+ except aiohttp.ClientConnectionError as exp:
199
+ # Network issue. If it is a background task probably fine to log and skip, if there is a user tell him network is bad
200
+ ...
201
+ # A ClientResponseError carries the status and message, e.g.:
202
+ # print(exp.status, exp.message)
203
+ ```
204
+
205
+ ## Developing
206
+
207
+ ### Building
208
+
209
+ ### Requirements
210
+
211
+ * Git
212
+ * uv
213
+ * Python 3.11+
214
+
215
+ ### Steps
216
+
217
+ ```sh
218
+ git clone https://github.com/14rynx/Preston
219
+ cd Preston
220
+ uv sync
221
+ ```
222
+
223
+ ### Running tests
224
+
225
+ | | |
226
+ | --- | --- |
227
+ | No coverage | `uv run pytest`
228
+ | Coverage printout | `uv run pytest --cov=preston` |
229
+ | Coverage report | `uv run pytest --cov=preston --cov-report=html` |
230
+
231
+ ### Releasing
232
+
233
+ 1. Bump `version` in `pyproject.toml` and commit.
234
+ 2. Tag and push: `git tag v5.0.1 && git push origin v5.0.1`.
235
+
236
+ CI runs the tests and, if they pass, publishes to PyPI via trusted publishing.
237
+
238
+ ## License
239
+
240
+ Licensed under MIT ([LICENSE](LICENSE)).
241
+
242
+ ## Contributing
243
+
244
+ PRs are welcome. Please follow PEP8 (I'm lenient on E501) and use [Google-style docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html#example-google).
@@ -0,0 +1,7 @@
1
+ preston/__init__.py,sha256=rJgvIqDHIytGDqKDzuAz3IcOzjaeJN66SoaCJVjIKrM,130
2
+ preston/cache.py,sha256=UpVhcQmA7GhtMOx7eUVIoYWifp1XeXtZ0AhMmrHvxBo,3255
3
+ preston/preston.py,sha256=ScrfRtm39E9bg8TYxCQP6dY3sphXNba1XcTT_u4Aa8o,20057
4
+ preston_async-5.0.0.dist-info/METADATA,sha256=fYb_9d_kgLpx3CyQKTudxvhMfyRt8ucuobwO1cems0k,8828
5
+ preston_async-5.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ preston_async-5.0.0.dist-info/licenses/LICENSE,sha256=q1roeeQYxcwrU5l2BtLo13SwNPA7GcjPF6tNjt0Llps,1080
7
+ preston_async-5.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,8 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2016 Matt Boulanger
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.