-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
298 lines (246 loc) · 9.68 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Final, Self
from aiohttp_client_cache.backends.sqlite import SQLiteBackend
from aiohttp_client_cache.session import CachedSession
from loguru import logger
from akasha.models.category import LeaderboardCategory
from akasha.models.leaderboard import LeaderboardPaginator
from .enums import Language
from .errors import DESC_TO_ERROR, AkashaAPIError, InvalidAPIRequestError
from .models import Leaderboard, UserCalc
from .models.artifact import Artifact
if TYPE_CHECKING:
from collections.abc import Sequence
__all__ = ("AkashaAPI",)
class AkashaAPI:
BASE_URL: Final[str] = "https://akasha.cv/api"
def __init__(
self,
lang: Language = Language.ENGLISH,
headers: dict[str, Any] | None = None,
cache_name: str = "./.cache/akasha-py.db",
cache_ttl: int = 360,
debug: bool = False,
) -> None:
self._lang = lang
self._headers = headers or {"User-Agent": "akasha-py"}
self._cache_name = cache_name
self._cache_ttl = cache_ttl
self._session: CachedSession | None = None
self.debug = debug
async def __aenter__(self) -> Self:
await self.start()
return self
async def __aexit__(self, exc_type, exc_value, traceback) -> None: # noqa: ANN001
await self.close()
async def start(self) -> None:
cache = SQLiteBackend(self._cache_name, expire_after=self._cache_ttl)
self._session = CachedSession(cache=cache)
async def close(self) -> None:
if self._session is None:
return
await self._session.close()
def _raise_for_error(self, data: list[dict[str, Any]] | dict[str, Any]) -> None:
if isinstance(data, list):
return
if "I want" in data.get("message", ""):
msg = "Invalid API request"
raise InvalidAPIRequestError(msg, data["message"])
if (error := data.get("error")) is not None:
if (message := data.get("message")) is not None:
title = message
description = error
else:
title = error["title"]
description = error["description"]
if (error_class := DESC_TO_ERROR.get(description)) is not None:
raise error_class(title, description)
raise AkashaAPIError(title, description)
async def _request(
self,
endpoint: str,
use_cache: bool,
*,
params: dict[str, Any] | None = None,
return_raw: bool = False,
) -> Any:
if self._session is None:
msg = f"Session is not started, call {self.__class__.__name__}.start() first."
raise RuntimeError(msg)
url = f"{self.BASE_URL}/{endpoint}"
params = params or {}
if self.debug:
logger.debug(f"Requesting {url} with params {params}")
if not use_cache:
async with self._session.disabled(), self._session.get(url, params=params) as response:
response.raise_for_status()
data = await response.json()
else:
async with self._session.get(url, params=params) as response:
response.raise_for_status()
data = await response.json()
if return_raw:
return data
data = data.get("data", data)
self._raise_for_error(data)
return data
async def get_calculations_for_user(
self, uid: int, *, use_cache: bool = True
) -> list[UserCalc]:
"""Get the calculations for a user.
Args:
uid: The user ID.
use_cache: Whether to use the cache.
"""
data = await self._request(f"getCalculationsForUser/{uid}", use_cache=use_cache)
user_calcs = [UserCalc(**calc) for calc in data]
strings: set[str] = set()
for user_calc in user_calcs:
strings.add(user_calc.name)
for calc in user_calc.calculations:
strings.add(calc.weapon.name)
translations = await self.get_translations(list(strings))
for user_calc in user_calcs:
user_calc.name = translations.get(user_calc.name.lower(), user_calc.name)
for calc in user_calc.calculations:
calc.weapon.name = translations.get(calc.weapon.name.lower(), calc.weapon.name)
return user_calcs
async def _fetch_leaderboards(
self,
calculation_id: int,
page: int,
page_size: int,
p: str,
variant: str | None,
uids: Sequence[int] | None,
use_cache: bool,
) -> list[Leaderboard]:
data = await self._request(
"leaderboards",
params={
"calculationId": calculation_id,
"size": page_size,
"page": page,
"sort": "calculation.result",
"order": -1,
"variant": variant or "",
"p": p,
"uids": f"[uid]{'[uid]'.join(map(str, uids))}" if uids else "",
"filter": "[all]1" if uids else "",
},
use_cache=use_cache,
)
return [Leaderboard(**lb) for lb in data]
def get_leaderboards(
self,
calculation_id: int,
*,
max_page: int,
page_size: int = 20,
variant: str | None = None,
uids: Sequence[int] | None = None,
use_cache: bool = True,
) -> LeaderboardPaginator:
"""Get a leaderboard paginator for a calculation.
Args:
calculation_id: The calculation ID.
max_page: The maximum number of pages to return.
page_size: The number of leaderboards to return per page.
variant: The variant of the leaderboard, e.g. 160er.
uids: The UIDs of the players to get the leaderboard for.
use_cache: Whether to use the cache.
"""
return LeaderboardPaginator(
self._fetch_leaderboards, calculation_id, page_size, max_page, variant, uids, use_cache
)
async def refresh_user(self, uid: int) -> None:
"""Refresh the Enka data of a player.
Args:
uid: The UID of the player.
"""
await self._request(f"user/refresh/{uid}", use_cache=False)
async def get_user(self, uid: int, *, use_cache: bool = True) -> None:
"""Get the user data.
Args:
uid: The UID of the player.
use_cache: Whether to use the cache.
"""
msg = "This method is not implemented yet."
raise NotImplementedError(msg)
await self._request(f"user/{uid}", use_cache=use_cache)
async def get_translations(self, words: list[str], *, use_cache: bool = True) -> dict[str, str]:
"""Get the translations for a list of words.
Args:
words: The list of words to translate.
use_cache: Whether to use the cache.
Returns:
A dictionary of the translations. Key is word.lower(), value is the translation.
"""
if self._lang is Language.ENGLISH:
return {word.lower(): word for word in words}
data = await self._request(
f"textmap/{self._lang.value}", use_cache=use_cache, params={"words[]": words}
)
return data["translation"]
async def translate(self, word: str) -> str:
"""Translate a word.
Do not use this method for multiple translations, use get_translations instead.
Args:
word: The word to translate.
Returns:
The translation of the word.
"""
if self._lang is Language.ENGLISH:
return word
return (await self.get_translations([word]))[word.lower()]
async def get_artifacts(self, uid: int, md5: str, *, use_cache: bool = True) -> list[Artifact]:
"""Get the artifacts of a build.
Args:
uid: The UID of the owner of the build.
md5: The MD5 hash of the build.
use_cache: Whether to use the cache.
"""
data = await self._request(f"artifacts/{uid}/{md5}", use_cache=use_cache)
return [Artifact(**artifact) for artifact in data]
async def get_categories(self, character_id: str) -> list[LeaderboardCategory]:
"""Get leaderboard categories of a character based on their ID.
Args:
character_id: The character ID.
"""
data = await self._request(
"v2/leaderboards/categories",
use_cache=True,
params={"characterId": character_id},
)
return [LeaderboardCategory(**category) for category in data]
async def get_collection_size(self, hash_: str, *, variant: str) -> int:
"""Get the size of a collection.
Args:
hash_: The hash of the collection.
variant: The variant of the collection.
"""
data = await self._request(
"getCollectionSize",
use_cache=True,
params={"hash": hash_, "variant": variant},
return_raw=True,
)
return data["totalRows"]
async def get_leaderboard_total_size(self, calculation_id: int) -> int:
"""Get the total size of a leaderboard.
Args:
calculation_id: The calculation ID.
"""
data = await self._request(
"leaderboards",
use_cache=True,
params={
"calculationId": calculation_id,
"sort": "calculation.result",
"order": -1,
"size": 1,
"page": 1,
},
return_raw=True,
)
return await self.get_collection_size(data["totalRowsHash"], variant="charactersLb")