akef 0.3.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.
- akef/__init__.py +19 -0
- akef/cache.py +36 -0
- akef/client.py +578 -0
- akef/constants.py +17 -0
- akef/enka/__init__.py +13 -0
- akef/enka/build.py +175 -0
- akef/enka/client.py +60 -0
- akef/enka/gamedata.py +196 -0
- akef/enka/player.py +61 -0
- akef/enka/profile.py +337 -0
- akef/enka/skport.py +259 -0
- akef/enka/stats.py +307 -0
- akef/errors.py +54 -0
- akef/models/__init__.py +99 -0
- akef/models/account.py +78 -0
- akef/models/base.py +40 -0
- akef/models/card.py +664 -0
- akef/models/extra.py +207 -0
- akef/models/game.py +113 -0
- akef/models/pulls.py +149 -0
- akef/py.typed +0 -0
- akef/signing.py +20 -0
- akef/wiki.py +193 -0
- akef-0.3.0.dist-info/METADATA +289 -0
- akef-0.3.0.dist-info/RECORD +28 -0
- akef-0.3.0.dist-info/WHEEL +5 -0
- akef-0.3.0.dist-info/licenses/LICENSE +21 -0
- akef-0.3.0.dist-info/top_level.txt +1 -0
akef/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from akef.client import Client
|
|
2
|
+
from akef.enka import Enka, EnkaProfile, GameData
|
|
3
|
+
from akef.errors import (
|
|
4
|
+
AkefError,
|
|
5
|
+
AlreadyCheckedIn,
|
|
6
|
+
APIError,
|
|
7
|
+
AuthError,
|
|
8
|
+
GameDataError,
|
|
9
|
+
MissingGameData,
|
|
10
|
+
NetworkError,
|
|
11
|
+
NoRoleError,
|
|
12
|
+
PlayerNotFound,
|
|
13
|
+
ShowcaseEmpty,
|
|
14
|
+
UnknownCharacter,
|
|
15
|
+
)
|
|
16
|
+
from akef.models import * # noqa: F401,F403
|
|
17
|
+
from akef.wiki import WikiPage, WikiPart, wiki_page
|
|
18
|
+
|
|
19
|
+
__version__ = "0.3.0"
|
akef/cache.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Awaitable, Callable
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TTLCache:
|
|
9
|
+
def __init__(self):
|
|
10
|
+
self._data: dict[Any, tuple[float, Any]] = {}
|
|
11
|
+
self._running: dict[Any, asyncio.Future] = {}
|
|
12
|
+
|
|
13
|
+
async def get(self, key, ttl: float | Callable[[Any], float], fetch: Callable[[], Awaitable], keep: Callable[[Any], bool] = lambda v: True):
|
|
14
|
+
hit = self._data.get(key)
|
|
15
|
+
if hit and hit[0] > time.monotonic():
|
|
16
|
+
return hit[1]
|
|
17
|
+
running = self._running.get(key)
|
|
18
|
+
if running is not None:
|
|
19
|
+
return await asyncio.shield(running)
|
|
20
|
+
task = asyncio.ensure_future(fetch())
|
|
21
|
+
self._running[key] = task
|
|
22
|
+
try:
|
|
23
|
+
value = await task
|
|
24
|
+
finally:
|
|
25
|
+
self._running.pop(key, None)
|
|
26
|
+
if keep(value):
|
|
27
|
+
life = ttl(value) if callable(ttl) else ttl
|
|
28
|
+
self._data[key] = (time.monotonic() + life, value)
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
def drop(self, match: Callable[[Any], bool] = lambda key: True) -> None:
|
|
32
|
+
for key in [k for k in self._data if match(k)]:
|
|
33
|
+
del self._data[key]
|
|
34
|
+
|
|
35
|
+
def __len__(self) -> int:
|
|
36
|
+
return len(self._data)
|
akef/client.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import difflib
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
from datetime import date, datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlencode
|
|
14
|
+
|
|
15
|
+
import aiohttp
|
|
16
|
+
|
|
17
|
+
from akef import constants as c
|
|
18
|
+
from akef.cache import TTLCache
|
|
19
|
+
from akef.errors import AlreadyCheckedIn, APIError, AuthError, NetworkError, NoRoleError, UnknownCharacter
|
|
20
|
+
from akef.models import (
|
|
21
|
+
OPERATOR_BANNERS,
|
|
22
|
+
Account,
|
|
23
|
+
Attendance,
|
|
24
|
+
Banner,
|
|
25
|
+
Card,
|
|
26
|
+
Character,
|
|
27
|
+
CheckIn,
|
|
28
|
+
ContractDetail,
|
|
29
|
+
Enums,
|
|
30
|
+
IndieHard,
|
|
31
|
+
Inventory,
|
|
32
|
+
Notice,
|
|
33
|
+
Owned,
|
|
34
|
+
Profile,
|
|
35
|
+
Pull,
|
|
36
|
+
Pulls,
|
|
37
|
+
Role,
|
|
38
|
+
WikiItem,
|
|
39
|
+
)
|
|
40
|
+
from akef.signing import sign
|
|
41
|
+
|
|
42
|
+
ALREADY_CHECKED_IN = 10001
|
|
43
|
+
# same code skport uses for "already checked in"
|
|
44
|
+
LOGIN_GONE = 10001
|
|
45
|
+
ATTENDANCE = "/web/v1/game/endfield/attendance"
|
|
46
|
+
CACHE_FOR = {
|
|
47
|
+
"/api/v1/game/endfield/card/detail": 60,
|
|
48
|
+
"/api/v1/game/endfield/card/char": 60,
|
|
49
|
+
"/api/v1/game/endfield/card/indie-hard": 300,
|
|
50
|
+
"/api/v1/game/endfield/card/crisis-contract": 300,
|
|
51
|
+
ATTENDANCE: 60,
|
|
52
|
+
"/web/v2/user": 300,
|
|
53
|
+
"/web/v1/game/endfield/enums": 3600,
|
|
54
|
+
"/web/v1/wiki/char-pool": 600,
|
|
55
|
+
"/web/v1/wiki/weapon-pool": 600,
|
|
56
|
+
"/web/v1/wiki/item/catalog": 3600,
|
|
57
|
+
"/web/v1/wiki/item/info": 3600,
|
|
58
|
+
"/web/v1/game/endfield/team/user-game-data": 60,
|
|
59
|
+
}
|
|
60
|
+
WIKI = {"operators": 1, "weapons": 2, "threats": 3, "gear": 4, "facilities": 5, "items": 6, "essence": 15, "valuables": 16}
|
|
61
|
+
NEWS_LANG = {"en": "en-us", "ja": "ja-jp", "ko": "ko-kr", "zh_Hant": "zh-tw"}
|
|
62
|
+
|
|
63
|
+
log = logging.getLogger("akef")
|
|
64
|
+
CHAR_ID = re.compile(r"[0-9a-f]{32}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _key(name: str) -> str:
|
|
68
|
+
return re.sub(r"[\W_]+", "", name.casefold())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _json(text: str) -> dict:
|
|
72
|
+
try:
|
|
73
|
+
data = json.loads(text) if text else {}
|
|
74
|
+
except ValueError:
|
|
75
|
+
return {}
|
|
76
|
+
return data if isinstance(data, dict) else {}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Client:
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
token: str,
|
|
83
|
+
*,
|
|
84
|
+
lang: str = "en",
|
|
85
|
+
session: aiohttp.ClientSession | None = None,
|
|
86
|
+
timeout: float = 20,
|
|
87
|
+
login_file: str | Path | None = None,
|
|
88
|
+
cache: bool = True,
|
|
89
|
+
debug: bool = False,
|
|
90
|
+
):
|
|
91
|
+
self.token = token.strip()
|
|
92
|
+
self.lang = lang
|
|
93
|
+
self.cred: str | None = None
|
|
94
|
+
self.salt: str | None = None
|
|
95
|
+
self.user_id: str | None = None
|
|
96
|
+
self._session = session
|
|
97
|
+
self._owns_session = session is None
|
|
98
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
99
|
+
self._login_lock = asyncio.Lock()
|
|
100
|
+
self._roles: list[Role] | None = None
|
|
101
|
+
self._names: dict[str, dict[str, tuple[str, str]]] = {}
|
|
102
|
+
self.login_file = Path(login_file) if login_file else None
|
|
103
|
+
self.cache = cache
|
|
104
|
+
self.debug = debug
|
|
105
|
+
self._cache = TTLCache()
|
|
106
|
+
self._load_login()
|
|
107
|
+
|
|
108
|
+
async def __aenter__(self) -> "Client":
|
|
109
|
+
return self
|
|
110
|
+
|
|
111
|
+
async def __aexit__(self, *exc) -> None:
|
|
112
|
+
await self.close()
|
|
113
|
+
|
|
114
|
+
async def close(self) -> None:
|
|
115
|
+
if self._owns_session and self._session is not None and not self._session.closed:
|
|
116
|
+
await self._session.close()
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def session(self) -> aiohttp.ClientSession:
|
|
120
|
+
if self._session is None or self._session.closed:
|
|
121
|
+
self._session = aiohttp.ClientSession(timeout=self._timeout)
|
|
122
|
+
self._owns_session = True
|
|
123
|
+
return self._session
|
|
124
|
+
|
|
125
|
+
def _fingerprint(self) -> str:
|
|
126
|
+
return hashlib.sha256(self.token.encode()).hexdigest()
|
|
127
|
+
|
|
128
|
+
def _load_login(self) -> None:
|
|
129
|
+
if self.login_file is None:
|
|
130
|
+
return
|
|
131
|
+
try:
|
|
132
|
+
saved = json.loads(self.login_file.read_text(encoding="utf-8"))
|
|
133
|
+
except (OSError, ValueError):
|
|
134
|
+
return
|
|
135
|
+
if saved.get("token") == self._fingerprint():
|
|
136
|
+
self.cred, self.salt, self.user_id = saved.get("cred"), saved.get("salt"), saved.get("user_id")
|
|
137
|
+
if saved.get("roles") is not None:
|
|
138
|
+
self._roles = [Role.model_validate(r) for r in saved["roles"]]
|
|
139
|
+
|
|
140
|
+
def _save_login(self) -> None:
|
|
141
|
+
if self.login_file is None:
|
|
142
|
+
return
|
|
143
|
+
data = {"token": self._fingerprint(), "cred": self.cred, "salt": self.salt, "user_id": self.user_id}
|
|
144
|
+
if self._roles is not None:
|
|
145
|
+
data["roles"] = [r.model_dump(by_alias=True, mode="json") for r in self._roles]
|
|
146
|
+
try:
|
|
147
|
+
self.login_file.parent.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
self.login_file.write_text(json.dumps(data), encoding="utf-8")
|
|
149
|
+
except OSError:
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
def clear_cache(self) -> None:
|
|
153
|
+
self._cache.drop()
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def logged_in(self) -> bool:
|
|
157
|
+
return self.cred is not None and self.salt is not None
|
|
158
|
+
|
|
159
|
+
def _headers(self, account: bool = False) -> dict[str, str]:
|
|
160
|
+
headers = {"User-Agent": c.USER_AGENT, "Origin": c.ORIGIN, "Referer": c.ORIGIN + "/"}
|
|
161
|
+
headers["x-language" if account else "sk-language"] = self.lang
|
|
162
|
+
return headers
|
|
163
|
+
|
|
164
|
+
async def _send(self, method: str, url: str, headers: dict, body: str | None = None) -> tuple[int, str]:
|
|
165
|
+
# queries can carry tokens, so only the path ever reaches the log or an error
|
|
166
|
+
where = url.split("?", 1)[0]
|
|
167
|
+
started = time.perf_counter()
|
|
168
|
+
try:
|
|
169
|
+
async with self.session.request(method, url, headers=headers, data=body) as resp:
|
|
170
|
+
status, text = resp.status, await resp.text()
|
|
171
|
+
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
|
|
172
|
+
if self.debug:
|
|
173
|
+
log.warning("%s %s failed: %s", method, where, exc.__class__.__name__)
|
|
174
|
+
raise NetworkError(f"{method} {where} failed: {exc.__class__.__name__}") from exc
|
|
175
|
+
if self.debug:
|
|
176
|
+
log.info("%s %s -> %s in %.0fms", method, where, status, (time.perf_counter() - started) * 1000)
|
|
177
|
+
return status, text
|
|
178
|
+
|
|
179
|
+
async def _account(self, method: str, path: str, *, params: dict | None = None, payload: dict | None = None):
|
|
180
|
+
headers = self._headers(account=True)
|
|
181
|
+
body = None
|
|
182
|
+
if payload is not None:
|
|
183
|
+
body = json.dumps(payload, separators=(",", ":"))
|
|
184
|
+
headers["Content-Type"] = "application/json"
|
|
185
|
+
url = c.ACCOUNT_HOST + path + (f"?{urlencode(params)}" if params else "")
|
|
186
|
+
status, text = await self._send(method, url, headers, body)
|
|
187
|
+
data = _json(text)
|
|
188
|
+
if status != 200 or data.get("status") != 0:
|
|
189
|
+
raise AuthError(data.get("msg") or f"account token rejected (http {status})", code=data.get("status"))
|
|
190
|
+
return data.get("data") or {}
|
|
191
|
+
|
|
192
|
+
async def _zonai(
|
|
193
|
+
self,
|
|
194
|
+
method: str,
|
|
195
|
+
path: str,
|
|
196
|
+
*,
|
|
197
|
+
params: dict | None = None,
|
|
198
|
+
payload: dict | None = None,
|
|
199
|
+
role: Role | None = None,
|
|
200
|
+
signed: bool = True,
|
|
201
|
+
retry: bool = True,
|
|
202
|
+
) -> Any:
|
|
203
|
+
if signed and not self.logged_in:
|
|
204
|
+
await self.login()
|
|
205
|
+
|
|
206
|
+
query = urlencode(params) if params else ""
|
|
207
|
+
body = json.dumps(payload, separators=(",", ":")) if payload is not None else None
|
|
208
|
+
headers = self._headers()
|
|
209
|
+
if body is not None:
|
|
210
|
+
headers["Content-Type"] = "application/json"
|
|
211
|
+
if self.cred:
|
|
212
|
+
headers["cred"] = self.cred
|
|
213
|
+
if role is not None:
|
|
214
|
+
headers["sk-game-role"] = role.game_role
|
|
215
|
+
if signed:
|
|
216
|
+
# GETs sign the query string, POSTs sign the json body
|
|
217
|
+
headers.update(sign(path, body if body is not None else query, self.salt))
|
|
218
|
+
|
|
219
|
+
url = c.ZONAI_HOST + path + (f"?{query}" if query else "")
|
|
220
|
+
ttl = CACHE_FOR.get(path, 0) if self.cache and method == "GET" else 0
|
|
221
|
+
if ttl:
|
|
222
|
+
status, text = await self._cache.get(
|
|
223
|
+
(url, headers.get("sk-game-role"), self.lang),
|
|
224
|
+
ttl,
|
|
225
|
+
lambda: self._send(method, url, headers, body),
|
|
226
|
+
keep=lambda r: r[0] == 200 and _json(r[1]).get("code") == 0,
|
|
227
|
+
)
|
|
228
|
+
else:
|
|
229
|
+
status, text = await self._send(method, url, headers, body)
|
|
230
|
+
data = _json(text)
|
|
231
|
+
|
|
232
|
+
# stale salt -> 401, dead cred -> 200 with code 10001
|
|
233
|
+
gone = status == 401 or (data.get("code") == LOGIN_GONE and not (method == "POST" and path == ATTENDANCE))
|
|
234
|
+
if gone and signed and retry:
|
|
235
|
+
self.cred = self.salt = None
|
|
236
|
+
await self.login()
|
|
237
|
+
return await self._zonai(method, path, params=params, payload=payload, role=role, signed=signed, retry=False)
|
|
238
|
+
if gone and signed:
|
|
239
|
+
raise AuthError("skport refused the session", code=data.get("code", status))
|
|
240
|
+
|
|
241
|
+
if status != 200 or data.get("code") != 0:
|
|
242
|
+
raise APIError(data.get("message") or f"http {status}", code=data.get("code", status))
|
|
243
|
+
return data.get("data")
|
|
244
|
+
|
|
245
|
+
async def login(self) -> None:
|
|
246
|
+
async with self._login_lock:
|
|
247
|
+
if self.logged_in:
|
|
248
|
+
return
|
|
249
|
+
grant = await self._account(
|
|
250
|
+
"POST", "/user/oauth2/v2/grant", payload={"token": self.token, "appCode": c.APP_CODE, "type": 0}
|
|
251
|
+
)
|
|
252
|
+
data = await self._zonai(
|
|
253
|
+
"POST", "/web/v1/user/auth/generate_cred_by_code", payload={"kind": 1, "code": grant["code"]}, signed=False
|
|
254
|
+
)
|
|
255
|
+
self.cred = data["cred"]
|
|
256
|
+
self.user_id = data.get("userId")
|
|
257
|
+
self.salt = data.get("token") or await self.refresh()
|
|
258
|
+
self._save_login()
|
|
259
|
+
|
|
260
|
+
async def refresh(self) -> str:
|
|
261
|
+
data = await self._zonai("GET", "/web/v1/auth/refresh", signed=False)
|
|
262
|
+
self.salt = data["token"]
|
|
263
|
+
return self.salt
|
|
264
|
+
|
|
265
|
+
async def account(self, *, raw: bool = False) -> Account | dict:
|
|
266
|
+
data = await self._account("GET", "/user/info/v1/basic", params={"token": self.token})
|
|
267
|
+
return data if raw else Account.model_validate(data)
|
|
268
|
+
|
|
269
|
+
async def profile(self, *, raw: bool = False) -> Profile | dict:
|
|
270
|
+
data = await self._zonai("GET", "/web/v2/user")
|
|
271
|
+
return data if raw else Profile.model_validate(data)
|
|
272
|
+
|
|
273
|
+
async def roles(self, *, raw: bool = False) -> list[Role] | dict:
|
|
274
|
+
data = await self._zonai("GET", "/api/v1/game/player/binding")
|
|
275
|
+
if raw:
|
|
276
|
+
return data
|
|
277
|
+
roles = []
|
|
278
|
+
for app in data.get("list") or []:
|
|
279
|
+
if app.get("appCode") != "endfield":
|
|
280
|
+
continue
|
|
281
|
+
for binding in app.get("bindingList") or []:
|
|
282
|
+
roles.extend(Role.model_validate(r) for r in binding.get("roles") or [])
|
|
283
|
+
self._roles = roles
|
|
284
|
+
self._save_login()
|
|
285
|
+
return roles
|
|
286
|
+
|
|
287
|
+
async def role(self, uid: int | str | None = None) -> Role:
|
|
288
|
+
roles = self._roles if self._roles is not None else await self.roles()
|
|
289
|
+
if not roles:
|
|
290
|
+
raise NoRoleError("no Endfield account is bound to this SKPORT login")
|
|
291
|
+
if uid is None:
|
|
292
|
+
return next((r for r in roles if r.is_default), roles[0])
|
|
293
|
+
found = next((r for r in roles if r.uid == str(uid)), None)
|
|
294
|
+
if found is None:
|
|
295
|
+
raise NoRoleError(f"UID {uid} isn't bound to this SKPORT login")
|
|
296
|
+
return found
|
|
297
|
+
|
|
298
|
+
async def card(self, uid: int | str | None = None, *, raw: bool = False) -> Card | dict:
|
|
299
|
+
role = await self.role(uid)
|
|
300
|
+
data = await self._zonai(
|
|
301
|
+
"GET",
|
|
302
|
+
"/api/v1/game/endfield/card/detail",
|
|
303
|
+
params={"roleId": role.uid, "serverId": role.server_id},
|
|
304
|
+
role=role,
|
|
305
|
+
)
|
|
306
|
+
return data if raw else Card.model_validate(data["detail"])
|
|
307
|
+
|
|
308
|
+
async def character(
|
|
309
|
+
self,
|
|
310
|
+
who: str | list[str],
|
|
311
|
+
uid: int | str | None = None,
|
|
312
|
+
*,
|
|
313
|
+
raw: bool = False,
|
|
314
|
+
) -> Character | dict | list[Character] | list[dict]:
|
|
315
|
+
role = await self.role(uid)
|
|
316
|
+
many = not isinstance(who, str)
|
|
317
|
+
wanted = list(who) if many else [who]
|
|
318
|
+
loaded: dict[str, dict] = {}
|
|
319
|
+
ids = [await self._char_id(w, role, loaded) for w in wanted]
|
|
320
|
+
|
|
321
|
+
async def one(char_id):
|
|
322
|
+
if char_id in loaded:
|
|
323
|
+
return {"detail": loaded[char_id]}
|
|
324
|
+
return await self._zonai(
|
|
325
|
+
"GET",
|
|
326
|
+
"/api/v1/game/endfield/card/char",
|
|
327
|
+
params={"roleId": role.uid, "serverId": role.server_id, "charId": char_id},
|
|
328
|
+
role=role,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
found = await asyncio.gather(*(one(i) for i in ids))
|
|
332
|
+
out = []
|
|
333
|
+
for name, data in zip(wanted, found):
|
|
334
|
+
if not data.get("detail"):
|
|
335
|
+
raise UnknownCharacter(f"{name!r} isn't on UID {role.uid}")
|
|
336
|
+
out.append(data if raw else Character.model_validate(data["detail"]))
|
|
337
|
+
return out if many else out[0]
|
|
338
|
+
|
|
339
|
+
async def _char_id(self, who: str, role: Role, loaded: dict[str, dict]) -> str:
|
|
340
|
+
if CHAR_ID.fullmatch(who):
|
|
341
|
+
return who
|
|
342
|
+
names = self._names.get(role.uid)
|
|
343
|
+
if names is None or _key(who) not in names:
|
|
344
|
+
card = await self.card(role.uid, raw=True)
|
|
345
|
+
loaded.update({ch["id"]: ch for ch in card["detail"]["chars"]})
|
|
346
|
+
names = {_key(ch["charData"]["name"]): (ch["id"], ch["charData"]["name"]) for ch in card["detail"]["chars"]}
|
|
347
|
+
self._names[role.uid] = names
|
|
348
|
+
if _key(who) in names:
|
|
349
|
+
return names[_key(who)][0]
|
|
350
|
+
close = difflib.get_close_matches(_key(who), names, n=1)
|
|
351
|
+
hint = f", did you mean {names[close[0]][1]!r}?" if close else ""
|
|
352
|
+
raise UnknownCharacter(f"no operator called {who!r} on UID {role.uid}{hint}")
|
|
353
|
+
|
|
354
|
+
async def monument(self, uid: int | str | None = None, *, raw: bool = False) -> IndieHard | dict:
|
|
355
|
+
role = await self.role(uid)
|
|
356
|
+
data = await self._zonai(
|
|
357
|
+
"GET",
|
|
358
|
+
"/api/v1/game/endfield/card/indie-hard",
|
|
359
|
+
params={"roleId": role.uid, "serverId": role.server_id},
|
|
360
|
+
role=role,
|
|
361
|
+
)
|
|
362
|
+
return data if raw else IndieHard.model_validate(data["indieHard"])
|
|
363
|
+
|
|
364
|
+
async def contract(self, uid: int | str | None = None, *, raw: bool = False) -> ContractDetail | dict:
|
|
365
|
+
role = await self.role(uid)
|
|
366
|
+
data = await self._zonai(
|
|
367
|
+
"GET",
|
|
368
|
+
"/api/v1/game/endfield/card/crisis-contract",
|
|
369
|
+
params={"roleId": role.uid, "serverId": role.server_id},
|
|
370
|
+
role=role,
|
|
371
|
+
)
|
|
372
|
+
return data if raw else ContractDetail.model_validate(data["crisisContract"])
|
|
373
|
+
|
|
374
|
+
async def _gacha_token(self, role: Role) -> str:
|
|
375
|
+
async def fetch():
|
|
376
|
+
grant = await self._account(
|
|
377
|
+
"POST", "/user/oauth2/v2/grant", payload={"token": self.token, "appCode": c.GACHA_APP_CODE, "type": 1}
|
|
378
|
+
)
|
|
379
|
+
# pull history wants the account-level uid, not the in-game one
|
|
380
|
+
bindings = await self._plain("GET", c.BINDING_HOST + "/account/binding/v1/binding_list",
|
|
381
|
+
params={"token": grant["token"], "appCode": "endfield"})
|
|
382
|
+
account_uid = None
|
|
383
|
+
for app in bindings.get("list") or []:
|
|
384
|
+
for binding in app.get("bindingList") or []:
|
|
385
|
+
if any(r.get("roleId") == role.uid for r in binding.get("roles") or []):
|
|
386
|
+
account_uid = binding["uid"]
|
|
387
|
+
if account_uid is None:
|
|
388
|
+
raise NoRoleError(f"UID {role.uid} has no pull history on this login")
|
|
389
|
+
data = await self._plain("POST", c.BINDING_HOST + "/account/binding/v1/u8_token_by_uid",
|
|
390
|
+
payload={"uid": account_uid, "token": grant["token"]})
|
|
391
|
+
return data["token"]
|
|
392
|
+
|
|
393
|
+
return await self._cache.get(("gacha token", role.uid), 600, fetch)
|
|
394
|
+
|
|
395
|
+
async def _plain(self, method: str, url: str, *, params: dict | None = None, payload: dict | None = None):
|
|
396
|
+
headers = {"User-Agent": c.USER_AGENT}
|
|
397
|
+
body = None
|
|
398
|
+
if payload is not None:
|
|
399
|
+
body = json.dumps(payload, separators=(",", ":"))
|
|
400
|
+
headers["Content-Type"] = "application/json"
|
|
401
|
+
status, text = await self._send(method, url + (f"?{urlencode(params)}" if params else ""), headers, body)
|
|
402
|
+
data = _json(text)
|
|
403
|
+
if status != 200 or data.get("code", data.get("status", 0)) != 0:
|
|
404
|
+
message = data.get("msg") or data.get("message") or f"http {status}"
|
|
405
|
+
raise APIError(str(message), code=data.get("code", status))
|
|
406
|
+
return data.get("data") or {}
|
|
407
|
+
|
|
408
|
+
async def _pull_pages(self, path: str, params: dict, stop: int, after_ms: int) -> list[dict]:
|
|
409
|
+
out, seq = [], ""
|
|
410
|
+
while True:
|
|
411
|
+
page = await self._plain("GET", c.WEBVIEW_HOST + path, params=dict(params, **({"seq_id": seq} if seq else {})))
|
|
412
|
+
rows = page.get("list") or []
|
|
413
|
+
# pages come newest first, so the first old row means everything after it is old too
|
|
414
|
+
fresh = [r for r in rows if int(r.get("seqId") or 0) > stop and int(r.get("gachaTs") or 0) >= after_ms]
|
|
415
|
+
out += fresh
|
|
416
|
+
if not page.get("hasMore") or not rows or len(fresh) < len(rows):
|
|
417
|
+
return out
|
|
418
|
+
seq = rows[-1]["seqId"]
|
|
419
|
+
|
|
420
|
+
async def pulls(
|
|
421
|
+
self,
|
|
422
|
+
uid: int | str | None = None,
|
|
423
|
+
*,
|
|
424
|
+
since: Pulls | None = None,
|
|
425
|
+
after: date | datetime | None = None,
|
|
426
|
+
raw: bool = False,
|
|
427
|
+
) -> Pulls | dict:
|
|
428
|
+
role = await self.role(uid)
|
|
429
|
+
if since is not None and since.uid and since.uid != role.uid:
|
|
430
|
+
raise ValueError(f"those pulls belong to UID {since.uid}, not {role.uid}")
|
|
431
|
+
if isinstance(after, datetime):
|
|
432
|
+
after_ms = int(after.timestamp() * 1000)
|
|
433
|
+
elif isinstance(after, date):
|
|
434
|
+
after_ms = int(datetime(after.year, after.month, after.day, tzinfo=timezone.utc).timestamp() * 1000)
|
|
435
|
+
else:
|
|
436
|
+
after_ms = 0
|
|
437
|
+
base = {"lang": "en-us", "token": await self._gacha_token(role), "server_id": role.server_id}
|
|
438
|
+
known = since.last_seq if since else {}
|
|
439
|
+
pools = await self._plain("GET", c.WEBVIEW_HOST + "/api/record/weapon/pool", params=base)
|
|
440
|
+
pool_ids = [p["poolId"] for p in pools] if isinstance(pools, list) else []
|
|
441
|
+
|
|
442
|
+
operator_pages = await asyncio.gather(*(
|
|
443
|
+
self._pull_pages("/api/record/char", dict(base, pool_type=f"E_CharacterGachaPoolType_{kind.title()}"),
|
|
444
|
+
known.get(kind, 0), after_ms)
|
|
445
|
+
for kind in OPERATOR_BANNERS
|
|
446
|
+
))
|
|
447
|
+
weapon_pages = await asyncio.gather(*(
|
|
448
|
+
self._pull_pages("/api/record/weapon", dict(base, pool_id=pool), known.get(pool, 0), after_ms)
|
|
449
|
+
for pool in pool_ids
|
|
450
|
+
))
|
|
451
|
+
if raw:
|
|
452
|
+
return {"operators": dict(zip(OPERATOR_BANNERS, operator_pages)), "weapons": dict(zip(pool_ids, weapon_pages))}
|
|
453
|
+
|
|
454
|
+
result = Pulls(
|
|
455
|
+
uid=role.uid,
|
|
456
|
+
operators=list(since.operators) if since else [],
|
|
457
|
+
weapons=list(since.weapons) if since else [],
|
|
458
|
+
gifts=list(since.gifts) if since else [],
|
|
459
|
+
)
|
|
460
|
+
for kind, rows in zip(OPERATOR_BANNERS, operator_pages):
|
|
461
|
+
for row in rows:
|
|
462
|
+
pull = Pull.model_validate(dict(row, banner=kind))
|
|
463
|
+
(result.operators if pull.kind == "draw" else result.gifts).append(pull)
|
|
464
|
+
for rows in weapon_pages:
|
|
465
|
+
for row in rows:
|
|
466
|
+
pull = Pull.model_validate(dict(row, banner=row.get("poolType", "")))
|
|
467
|
+
(result.weapons if pull.kind == "draw" else result.gifts).append(pull)
|
|
468
|
+
for group in (result.operators, result.weapons, result.gifts):
|
|
469
|
+
group.sort(key=lambda p: p.seq_id)
|
|
470
|
+
return result
|
|
471
|
+
|
|
472
|
+
async def news(self, *, raw: bool = False) -> list[Notice] | dict:
|
|
473
|
+
params = {"lang": NEWS_LANG.get(self.lang, "en-us"), "platform": "Windows", "channel": 6, "type": 0,
|
|
474
|
+
"code": c.BULLETIN_CODE, "hideDetail": 0, "server": 3}
|
|
475
|
+
|
|
476
|
+
async def fetch():
|
|
477
|
+
return await self._plain("GET", c.GAME_HUB_HOST + "/bulletin/v2/aggregate", params=params)
|
|
478
|
+
|
|
479
|
+
data = await self._cache.get(("news", self.lang), 600, fetch) if self.cache else await fetch()
|
|
480
|
+
if raw:
|
|
481
|
+
return data
|
|
482
|
+
notices = [Notice.model_validate(n) for n in data.get("list") or []]
|
|
483
|
+
return sorted(notices, key=lambda n: n.start_at.timestamp() if n.start_at else 0, reverse=True)
|
|
484
|
+
|
|
485
|
+
async def wiki(self, kind: str, *, raw: bool = False) -> list[WikiItem] | dict:
|
|
486
|
+
if kind not in WIKI:
|
|
487
|
+
raise ValueError(f"wiki kind should be one of {sorted(WIKI)}")
|
|
488
|
+
sub = str(WIKI[kind])
|
|
489
|
+
data = await self._zonai("GET", "/web/v1/wiki/item/catalog", params={"typeMainId": 1, "typeSubId": sub})
|
|
490
|
+
if raw:
|
|
491
|
+
return data
|
|
492
|
+
items = [i for top in data.get("catalog") or [] for s in top.get("typeSub") or [] if s.get("id") == sub
|
|
493
|
+
for i in s.get("items") or []]
|
|
494
|
+
return [WikiItem.model_validate(i) for i in items]
|
|
495
|
+
|
|
496
|
+
async def wiki_index(self) -> dict[str, WikiItem]:
|
|
497
|
+
lists = await asyncio.gather(*(self.wiki(kind) for kind in WIKI))
|
|
498
|
+
return {item.id: item for items in lists for item in items}
|
|
499
|
+
|
|
500
|
+
async def wiki_item(self, item_id: int | str, *, raw: bool = False) -> WikiItem | dict:
|
|
501
|
+
data = await self._zonai("GET", "/web/v1/wiki/item/info", params={"id": item_id})
|
|
502
|
+
if raw:
|
|
503
|
+
return data
|
|
504
|
+
if not data.get("item"):
|
|
505
|
+
raise APIError(f"no wiki entry {item_id}")
|
|
506
|
+
return WikiItem.model_validate(data["item"])
|
|
507
|
+
|
|
508
|
+
async def inventory(self, uid: int | str | None = None, *, names: bool = True, raw: bool = False) -> Inventory | dict:
|
|
509
|
+
role = await self.role(uid)
|
|
510
|
+
data = await self._zonai("GET", "/web/v1/game/endfield/team/user-game-data",
|
|
511
|
+
params={"roleId": role.uid, "serverId": role.server_id}, role=role)
|
|
512
|
+
data = data.get("userGameData") or {}
|
|
513
|
+
if raw:
|
|
514
|
+
return data
|
|
515
|
+
known: dict[str, str] = {}
|
|
516
|
+
if names:
|
|
517
|
+
card, weapons = await asyncio.gather(self.card(role.uid), self.wiki("weapons"))
|
|
518
|
+
for op in card.chars:
|
|
519
|
+
known[op.id] = op.name
|
|
520
|
+
for e in op.equips:
|
|
521
|
+
known[e.equip_data.id] = e.equip_data.name
|
|
522
|
+
if op.tactical_item:
|
|
523
|
+
known[op.tactical_item.tactical_item_data.id] = op.tactical_item.tactical_item_data.name
|
|
524
|
+
known.update({w.game_id: w.name for w in weapons if w.game_id})
|
|
525
|
+
|
|
526
|
+
def owned(section, count_key=None):
|
|
527
|
+
out = []
|
|
528
|
+
for item_id, entry in (data.get(section) or {}).items():
|
|
529
|
+
if entry.get("owned") is False:
|
|
530
|
+
continue
|
|
531
|
+
count = int(entry.get(count_key) or 1) if count_key else 1
|
|
532
|
+
out.append(Owned(id=item_id, name=known.get(item_id, ""), count=count))
|
|
533
|
+
return sorted(out, key=lambda o: (not o.name, o.name, o.id))
|
|
534
|
+
|
|
535
|
+
return Inventory(
|
|
536
|
+
operators=owned("userChars"),
|
|
537
|
+
weapons=owned("userWeapons"),
|
|
538
|
+
gear=owned("userEquips", "ownedCount"),
|
|
539
|
+
tacticals=owned("userTacticalItems", "ownedCount"),
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
async def attendance(self, uid: int | str | None = None, *, raw: bool = False) -> Attendance | dict:
|
|
543
|
+
role = await self.role(uid)
|
|
544
|
+
data = await self._zonai("GET", ATTENDANCE, role=role)
|
|
545
|
+
return data if raw else Attendance.model_validate(data)
|
|
546
|
+
|
|
547
|
+
async def check_in(self, uid: int | str | None = None, *, raw: bool = False) -> CheckIn | dict:
|
|
548
|
+
role = await self.role(uid)
|
|
549
|
+
try:
|
|
550
|
+
data = await self._zonai("POST", ATTENDANCE, payload={}, role=role) or {}
|
|
551
|
+
except APIError as exc:
|
|
552
|
+
if exc.code != ALREADY_CHECKED_IN:
|
|
553
|
+
raise
|
|
554
|
+
# could also be a dead login, a GET tells them apart
|
|
555
|
+
cred = self.cred
|
|
556
|
+
await self._zonai("GET", ATTENDANCE, role=role)
|
|
557
|
+
if self.cred == cred:
|
|
558
|
+
raise AlreadyCheckedIn(exc.message, code=exc.code) from None
|
|
559
|
+
try:
|
|
560
|
+
data = await self._zonai("POST", ATTENDANCE, payload={}, role=role) or {}
|
|
561
|
+
except APIError as again:
|
|
562
|
+
if again.code == ALREADY_CHECKED_IN:
|
|
563
|
+
raise AlreadyCheckedIn(again.message, code=again.code) from None
|
|
564
|
+
raise
|
|
565
|
+
self._cache.drop(lambda key: ATTENDANCE in key[0])
|
|
566
|
+
return data if raw else CheckIn.model_validate(data)
|
|
567
|
+
|
|
568
|
+
async def enums(self, *, raw: bool = False) -> Enums | dict:
|
|
569
|
+
data = await self._zonai("GET", "/web/v1/game/endfield/enums")
|
|
570
|
+
return data if raw else Enums.model_validate(data)
|
|
571
|
+
|
|
572
|
+
async def char_banners(self, *, raw: bool = False) -> list[Banner] | dict:
|
|
573
|
+
data = await self._zonai("GET", "/web/v1/wiki/char-pool")
|
|
574
|
+
return data if raw else [Banner.model_validate(b) for b in data.get("list") or []]
|
|
575
|
+
|
|
576
|
+
async def weapon_banners(self, *, raw: bool = False) -> list[Banner] | dict:
|
|
577
|
+
data = await self._zonai("GET", "/web/v1/wiki/weapon-pool")
|
|
578
|
+
return data if raw else [Banner.model_validate(b) for b in data.get("list") or []]
|
akef/constants.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
ACCOUNT_HOST = "https://as.gryphline.com"
|
|
2
|
+
ZONAI_HOST = "https://zonai.skport.com"
|
|
3
|
+
ORIGIN = "https://game.skport.com"
|
|
4
|
+
|
|
5
|
+
APP_CODE = "6eb76d4e13aa36e6"
|
|
6
|
+
BINDING_HOST = "https://binding-api-account-prod.gryphline.com"
|
|
7
|
+
WEBVIEW_HOST = "https://ef-webview.gryphline.com"
|
|
8
|
+
GACHA_APP_CODE = "3dacefa138426cfe"
|
|
9
|
+
GAME_HUB_HOST = "https://game-hub.gryphline.com"
|
|
10
|
+
BULLETIN_CODE = "endfield_U35PW8"
|
|
11
|
+
GAME_ID = 3
|
|
12
|
+
PLATFORM = "3"
|
|
13
|
+
VNAME = "1.0.0"
|
|
14
|
+
|
|
15
|
+
USER_AGENT = (
|
|
16
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
|
|
17
|
+
)
|
akef/enka/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from akef.enka.build import Build, Essence, Gear, Owner, Skill, Tactical, Talent, Weapon
|
|
2
|
+
from akef.enka.client import Enka
|
|
3
|
+
from akef.enka.gamedata import GameData
|
|
4
|
+
from akef.enka.player import Badge, Player, Rostered
|
|
5
|
+
from akef.enka.profile import EnkaProfile, fetch_player, profile_from_enka
|
|
6
|
+
from akef.enka.skport import build_from_skport, player_from_skport
|
|
7
|
+
from akef.enka.stats import GearLine, Stats
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Badge", "Build", "Enka", "EnkaProfile", "Essence", "GameData", "Gear", "GearLine", "Owner", "Player",
|
|
11
|
+
"Rostered", "Skill", "Stats", "Tactical", "Talent", "Weapon", "build_from_skport", "fetch_player",
|
|
12
|
+
"player_from_skport", "profile_from_enka",
|
|
13
|
+
]
|