sekai 0.1.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.

Potentially problematic release.


This version of sekai might be problematic. Click here for more details.

sekai/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ import logging
2
+ import coloredlogs
3
+ import sys
4
+
5
+ coloredlogs.install(
6
+ level=logging.INFO,
7
+ fmt="%(asctime)s %(name)s [%(levelname).4s] %(message)s",
8
+ isatty=True,
9
+ stream=sys.stdout,
10
+ )
11
+
12
+ logging.basicConfig(
13
+ level=logging.INFO,
14
+ format="[%(levelname).4s] %(name)s %(message)s",
15
+ stream=sys.stdout,
16
+ )
17
+
18
+ logging.getLogger("httpx").setLevel(logging.WARNING)
19
+
20
+ from .api import API
sekai/api/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .api import API
sekai/api/api.py ADDED
@@ -0,0 +1,637 @@
1
+ import httpx
2
+ import jwt
3
+ import logging
4
+ import msgpack
5
+
6
+ from typing import Optional, Union
7
+ from uuid import uuid4
8
+
9
+ from ..constants import EMPTY
10
+ from ..models import DeviceInfo, SystemInfo
11
+ from ..utils import decrypt_and_unpack, encrypt_and_pack
12
+
13
+ class API:
14
+ game_version_url = "https://game-version.sekai-en.com"
15
+ def __init__(self, raise_on_non_20x: bool = True) -> None:
16
+ self.assetBundleHostHash = None
17
+ self.domain = None
18
+ self.raise_on_non_20x = raise_on_non_20x
19
+ if SystemInfo.app_version and SystemInfo.app_hash:
20
+ self.setup()
21
+ #region General Setup
22
+ def call(self,
23
+ method: str,
24
+ endpoint: str,
25
+ data: Optional[dict] = None,
26
+ return_response: bool = False,
27
+ raise_on_non_20x: Optional[bool] = None,
28
+ headers: Optional[dict] = None) -> dict | httpx.Response | None:
29
+ """Custom request wrapper to allow for easier calls
30
+
31
+ Args:
32
+ method (str)
33
+ endpoint (str)
34
+ data (dict, optional): Data/body. Defaults to None
35
+ return_response (bool): Whether to return an httpx.Response object or a dict. Defaults to False.
36
+ raise_on_non_20x (bool): Overrides self.raise_on_non_20x. Defaults to None
37
+ headers (dict, optional)
38
+
39
+ Returns:
40
+ dict | httpx.Response | None: None if status_code == 204
41
+ """
42
+ if data != EMPTY and data is not None:
43
+ body = encrypt_and_pack(data)
44
+ else:
45
+ body = data
46
+ self.client.headers["X-Request-ID"] = str(uuid4())
47
+ r = self.client.request(method, f"https://{self.domain}/{endpoint}", data=body if data else None, headers=headers)
48
+ if r.status_code not in [200, 201, 204, 409]:
49
+ print(endpoint, r.status_code, data)
50
+ try:
51
+ print(decrypt_and_unpack(r.content))
52
+ except: pass
53
+ if raise_on_non_20x == True or (raise_on_non_20x != False and self.raise_on_non_20x):
54
+ print(self.client.headers.get("X-Session-Token"))
55
+ print(r.headers.get("X-Session-Token"))
56
+ raise Exception
57
+
58
+ if "X-Session-Token" in r.headers:
59
+ self.client.headers["X-Session-Token"] = r.headers["X-Session-Token"]
60
+
61
+ if return_response:
62
+ return r
63
+
64
+ if r.status_code == 204: return
65
+
66
+ data = decrypt_and_unpack(r.content)
67
+ return data
68
+
69
+ def setup(self):
70
+ """Call various functions to set up the API"""
71
+ self._test_version()
72
+ self._create_session()
73
+ self.system()
74
+
75
+ def _test_version(self) -> bool:
76
+ """Sends a request to the game version server (default: game-version.sekai-en.com) to verify that the version and appHash are correct
77
+
78
+ Returns:
79
+ bool: True if version and appHash are correct, else False
80
+ """
81
+ r = httpx.get(f"{self.game_version_url}/{SystemInfo.app_version}/{SystemInfo.app_hash}")
82
+ if r.status_code != 200:
83
+ return False
84
+ try:
85
+ data = decrypt_and_unpack(r.content)
86
+ except msgpack.exceptions.ExtraData:
87
+ return False
88
+
89
+ self.profile = data["profile"] # should always be production
90
+ self.assetbundleHostHash = data["assetbundleHostHash"]
91
+ self.domain = data["domain"]
92
+ return True
93
+
94
+ def _create_session(self, device_info: Optional[DeviceInfo] = None):
95
+ if device_info is not None and not isinstance(device_info, DeviceInfo): raise TypeError
96
+ """Create an httpx.client with the necessary headers"""
97
+ if device_info is None:
98
+ device_info = DeviceInfo
99
+ self.client = httpx.Client()
100
+ self.client.headers = {k: v for k, v in {
101
+ "Accept": "application/octet-stream",
102
+ "Accept-Encoding": "deflate, gzip",
103
+ "Content-Type": "application/octet-stream",
104
+ "User-Agent": "UnityPlayer/2022.3.52f1 (UnityWebRequest/1.0, libcurl/8.10.1-DEV)",
105
+ "X-AI": "f8defa742a470b57b3c4d57de49dc08c",
106
+ "X-App-Version": SystemInfo.app_version,
107
+ "X-App-Hash": SystemInfo.app_hash,
108
+ "X-Asset-Version": SystemInfo.asset_version,
109
+ "X-Data-Version": SystemInfo.data_version,
110
+ "X-DeviceModel": device_info.device_model,
111
+ "X-Install-Id": str(device_info.install_id),
112
+ "X-Platform": device_info.platform,
113
+ "X-Request-ID": str(uuid4()),
114
+ "X-OperatingSystem": device_info.operating_system,
115
+ "X-Unity-Version": "2022.3.52f1",
116
+ }.items() if v is not None} # unholy. disgraceful.
117
+
118
+ def _update_version_headers(self) -> None:
119
+ self.client.headers.update({k: v for k, v in {
120
+ "X-App-Version": SystemInfo.app_version,
121
+ "X-App-Hash": SystemInfo.app_hash,
122
+ "X-Asset-Version": SystemInfo.asset_version,
123
+ "X-Data-Version": SystemInfo.data_version,
124
+ }.items() if v is not None})
125
+ #endregion
126
+ #region Internal Calls
127
+ def system(self) -> None:
128
+ """Calls the /api/system endpoint and updates system_info with relevant data"""
129
+ session_token = self.client.headers.get("X-Session-Token", None)
130
+ temp_headers = self.client.headers.copy()
131
+ temp_headers.pop("X-Session-Token", None)
132
+ self.client.headers = temp_headers
133
+ r = self.call(
134
+ "GET",
135
+ "api/system",
136
+ return_response=True,
137
+ raise_on_non_20x=False
138
+ )
139
+ data = decrypt_and_unpack(r.content)
140
+ match r.status_code:
141
+ case 200: pass
142
+ case 426:
143
+ logging.error(f"App version and/or hash is outdated, please update the app.")
144
+ exit(1)
145
+ case _:
146
+ logging.error(f"Calling /api/system returned a non-200 status code ({r.status_code}).")
147
+ print(data)
148
+ exit(1)
149
+ if data.get("appVersions")[-1]["appVersion"] != SystemInfo.app_version:
150
+ logging.error(f"App version is outdated. Expected {SystemInfo.app_version}, got {data.get('appVersions')[-1]['appVersion']}")
151
+ SystemInfo.update(data)
152
+ self._create_session()
153
+ if session_token:
154
+ self.client.headers["X-Session-Token"] = session_token
155
+
156
+ def ageinfo(self, user_id: int) -> dict:
157
+ """Calls the /api/user/na/{user_id}/ageinfo endpoint to get the stored "age info" (birth year, month and day that the user entered their age/registered, and approximate age)"""
158
+ return self.call(f"api/user/na/{user_id}/ageinfo")
159
+
160
+ def update_section(self, user_id: int, section: str, data: dict) -> dict:
161
+ return self.call(
162
+ "PATCH",
163
+ f"api/user/{user_id}",
164
+ data={section: data}
165
+ )
166
+
167
+ def suite(self, user_id: int) -> dict:
168
+ return self.call(
169
+ "GET",
170
+ f"api/suite/user/{user_id}?isForceAllReload=true"
171
+ )
172
+
173
+ def get_maintenance(self, module: str) -> bool:
174
+ self.client.headers["X-Request-ID"] = str(uuid4())
175
+ r = self.client.request("GET", f"https://{self.domain}/api/module-maintenance/{module}", data=None)
176
+ if r.status_code != 200:
177
+ logging.warning(f"Endpoint module-maintenance responded with a {r.status_code} status code. This is unexpected! Assuming there is no maintenance.\nPlease forward this information to Taggie on GitHub. https://github.com/tailhaver")
178
+ return False
179
+ data = decrypt_and_unpack(r.content)
180
+ return data.get("isOngoing", False)
181
+
182
+ #endregion
183
+ #region Account Creation + Transfer
184
+ def create_user(self, device_info: Optional[DeviceInfo] = None) -> dict:
185
+ """Calls the /api/user endpoint to create a user
186
+
187
+ Args:
188
+ device_info (DeviceInfo, optional), Defaults to None.
189
+
190
+ Returns:
191
+ dict: All user account data from the API
192
+ """
193
+ if device_info is None:
194
+ device_info = DeviceInfo
195
+ body = {
196
+ "platform": device_info.platform,
197
+ "deviceModel": device_info.device_model,
198
+ "operatingSystem": device_info.operating_system
199
+ }
200
+ return self.call("POST", "api/user", data=body)
201
+
202
+ def login_from_token(self, user_id: int, token: str, device_id: str) -> dict[str, str]:
203
+ """Attempts to log the user in using their known session token
204
+
205
+ Args:
206
+ user_id (int)
207
+ token (str)
208
+ device_id (str)
209
+
210
+ Returns:
211
+ dict: sessionToken, deviceId
212
+ """
213
+ body = {
214
+ "credential": token,
215
+ "deviceId": device_id
216
+ }
217
+ data = self.call("PUT", f"api/user/{user_id}/auth?refreshUpdatedResources=False", data=body)
218
+ self.client.headers["X-Session-Token"] = data["sessionToken"]
219
+
220
+ # "interesting" way to update dataVer assetVer etc
221
+ SystemInfo.direct_update({k: v for k, v in data.items() if "Version" in k})
222
+ self._update_version_headers()
223
+ return {
224
+ "sessionToken": data["sessionToken"],
225
+ "deviceId": data["deviceId"] if "deviceId" in data else device_id
226
+ }
227
+
228
+ def _transfer_id(self, transfer_id: str, password: str, login: bool = False, return_response: bool = False) -> httpx.Response:
229
+ """Base function for calling the inherit API
230
+
231
+ Args:
232
+ transfer_id (str): Transfer ID
233
+ password (str): Transfer password
234
+ login (bool, optional): True to log in, False to get user data from the ID Defaults to False.
235
+ return_response (bool, optional)
236
+
237
+ Returns:
238
+ httpx.Response: API response
239
+ """
240
+ jwt_key = "uYf0cGqbgapejhc8bhba6G1cf5BBznOZeDz9NyFWZOgiiYsfUVNLT3wRUpCH6iDe1umsreAYuo35s8TP"
241
+ payload = {
242
+ "inheritId": transfer_id,
243
+ "password": password
244
+ }
245
+ headers = {
246
+ "X-Inherit-Id-Verify-Token": jwt.encode(payload, jwt_key, algorithm="HS256"),
247
+ }
248
+ r = self.call(
249
+ "POST",
250
+ f"api/inherit/user/{transfer_id}?isExecuteInherit={login}&isAdult=True&tAge=18",
251
+ EMPTY,
252
+ return_response=return_response,
253
+ raise_on_non_20x=False,
254
+ headers=headers,
255
+ )
256
+
257
+ match r.status_code:
258
+ case 200:
259
+ pass
260
+ case 403:
261
+ logging.error("Transfer ID inherit failed with code 403. This is likely due to an incorrect password or the transfer ID not existing.")
262
+ raise
263
+ case _:
264
+ logging.error(f"Transfer ID inherit responded with response code {r.status_code}. This is not expected!\nPlease forward this information to Taggie on GitHub. https://github.com/tailhaver")
265
+ raise Exception
266
+
267
+ return r
268
+
269
+ def check_transfer_id(self, transfer_id: str, password: str) -> dict[str, dict]:
270
+ """Calls the inherit API to check an ID and returns the user data (if found)
271
+
272
+ Args:
273
+ transfer_id (str): Transfer ID
274
+ password (str): Transfer password
275
+
276
+ Returns:
277
+ dict[str, dict]
278
+ """
279
+ r = self._transfer_id(transfer_id, password, login=False, return_response=True)
280
+ response = decrypt_and_unpack(r.content)
281
+ return response
282
+
283
+ def login_from_transfer_id(self, transfer_id: str, password: str) -> dict:
284
+ """Attempts to log in using the transfer ID
285
+
286
+ Args:
287
+ transfer_id (str): Transfer ID
288
+ password (str): Transfer password
289
+
290
+ Returns:
291
+ dict: user data
292
+ """
293
+ return decrypt_and_unpack(
294
+ self._transfer_id(transfer_id, password, login=True, return_response=True).content
295
+ )
296
+
297
+ def create_transfer_id(self, user_id: int, password: str) -> dict:
298
+ data = self.call(
299
+ "PUT",
300
+ f"api/user/{user_id}/inherit",
301
+ data={"password": password}
302
+ )
303
+ return {
304
+ "transferId": data["userInherit"]["inheritId"],
305
+ "password": password
306
+ }
307
+ #endregion
308
+ #region Profile
309
+ def set_name(self, user_id: int, name: str) -> ...:
310
+ return self.update_section(user_id, "userGamedata", {"name": name})
311
+
312
+ def update_profile(self,
313
+ user_id: int,
314
+ bio: str,
315
+ honorIDs: list[int, int, int],
316
+ twitterId: str) -> ...:
317
+ return self.call(
318
+ "PUT",
319
+ f"api/user/{user_id}/profile",
320
+ data={
321
+ "userId": user_id,
322
+ "word": bio,
323
+ "honorId1": honorIDs[0] or None,
324
+ "honorId2": honorIDs[1] or None,
325
+ "honorId3": honorIDs[2] or None,
326
+ "twitterId": twitterId,
327
+ "profileImageType": "leader",
328
+ "profileImageId": None
329
+ }
330
+ )
331
+ #endregion
332
+ #region Refreshes
333
+ def check_login_bonus(self, user_id: int) -> list[dict]:
334
+ r = self.call(
335
+ "PUT",
336
+ f"api/user/{user_id}/home/refresh",
337
+ {"refreshableTypes": ["login_bonus"], "isAdult": True}
338
+ )
339
+ return r.get("userLoginBonuses", {})
340
+
341
+ def check_friend_requests(self, user_id: int):
342
+ return self.call(
343
+ "PUT",
344
+ f"api/user/{user_id}/home/refresh",
345
+ {"refreshableTypes": ["new_pending_friend_request"], "isAdult": True}
346
+ ).get("newPendingUserFriends")
347
+
348
+ def list_presents(self, user_id) -> dict:
349
+ return self.call(
350
+ "PUT",
351
+ f"api/user/{user_id}/home/refresh",
352
+ {"refreshableTypes": ["login_bonus"], "isAdult": True}
353
+ ).get("updatedResources", {}).get("userPresents", {})
354
+
355
+ def open_presents(self, user_id: int, present_ids: list[int]) -> dict:
356
+ return self.call(
357
+ "POST",
358
+ f"api/user/{user_id}/present",
359
+ data={"presentIds": present_ids}
360
+ )
361
+
362
+ def check_invitations(self, user_id: int) -> dict:
363
+ return self.call(
364
+ "PUT",
365
+ f"api/user/{user_id}/invitation"
366
+ )
367
+ #endregion
368
+ #region Inventory
369
+ def restore_energy(self, user_id: int, items: list[dict]) -> ...:
370
+ """
371
+ Args:
372
+ user_id (int)
373
+ items (list[dict]): list of dict with items {resourceId: int, resourceType: str, quantity: int}
374
+ """
375
+ raise NotImplementedError
376
+
377
+ def claim_mission(self, user_id: int, mission_type: str, mission_ids: list[int]) -> dict:
378
+ return self.call(
379
+ "PUT",
380
+ f"api/user/{user_id}/mission/{mission_type}",
381
+ data={"missionIds": mission_ids}
382
+ )
383
+
384
+ def set_favorited_stamps(self, user_id: int) -> dict:
385
+ raise NotImplementedError
386
+ #endregion
387
+ #region Cards
388
+ def train_card(self,
389
+ user_id: int,
390
+ card_id: int,
391
+ scores: list[int, int]) -> dict:
392
+ """Increase a cards level using practice scores
393
+
394
+ Args:
395
+ user_id (int)
396
+ card_id (int)
397
+ scores (list[int, int]): [Score ID, Count]
398
+
399
+ Common Score IDs:
400
+ 1 - Practice score (Beginner)
401
+ 2 - Practice score (Intermediate)
402
+ 3 - Practice score (Advanced)
403
+
404
+ Returns:
405
+ dict: _description_
406
+ """
407
+ data = {
408
+ 'costs': [
409
+ [{'resourceId': score[0], 'resourceType': 'practice_ticket', 'resourceLevel': 0, 'quantity': score[1]} for score in scores if len(score) == 2],
410
+ ]
411
+ }
412
+ return self.call(
413
+ "POST",
414
+ f"api/user/{user_id}/card/{card_id}/practice-ticket",
415
+ data=data
416
+ )
417
+ def increase_mastery_rank(self, user_id: int, card_id: int, mastery_levels: list[int]) -> int:
418
+ return self.call(
419
+ "POST",
420
+ f"api/user/{user_id}/card/{card_id}/master-lesson",
421
+ data={"masterLessonCostIds": mastery_levels},
422
+ return_response=True
423
+ ).status_code
424
+ #endregion
425
+ #region Character Info
426
+ def claim_character_rank_stamps(self, user_id: int, character_id: int) -> int:
427
+ return self.call(
428
+ "PUT",
429
+ f"api/user/{user_id}/character/{character_id}/mission",
430
+ data=EMPTY,
431
+ return_response=True
432
+ ).status_code
433
+ def set_costume(self,
434
+ user_id: int,
435
+ character_id: int,
436
+ head_costume_id: int,
437
+ body_costume_id: int,
438
+ hair_costume_id: int) -> None:
439
+ raise NotImplementedError
440
+ return self.call(
441
+ "PUT",
442
+ f"api/user/{user_id}/character-costume-3d/character/{character_id}/unit/{UNIT_ID}",
443
+ data={'headCostume3dId': head_costume_id, 'bodyCostume3dId': body_costume_id, 'hairCostume3dId': hair_costume_id}
444
+ )
445
+ #endregion
446
+ #region Reading/Stories
447
+ def read_area_conversation(self, user_id: int, conversation_id: int,) -> int:
448
+ return self.call(
449
+ "PUT",
450
+ f"api/user/{user_id}/action-set/{conversation_id}",
451
+ data=EMPTY,
452
+ return_response=True
453
+ ).status_code
454
+
455
+ def _read_story(self,
456
+ url: str,
457
+ skip: bool,
458
+ num_pages: int) -> httpx.Response:
459
+ self.call(
460
+ "POST",
461
+ url,
462
+ data=EMPTY
463
+ )
464
+ return self.call(
465
+ "POST",
466
+ f"{url}/log",
467
+ data={
468
+ "noSkip": not skip,
469
+ "useSkip": skip,
470
+ "autoFinish": False,
471
+ "useAuto": False,
472
+ "fastForward": False,
473
+ "voice": False,
474
+ "numPages": num_pages,
475
+ "continuousPlayStart": False,
476
+ "playMusicVideo": False,
477
+ "musicVocalId": 0,
478
+ "musicCategoryName":
479
+ "mv",
480
+ "musicVideoNoSkip": False,
481
+ "userStoryMusicPlays": []
482
+ },
483
+ return_response=True,
484
+ raise_on_non_20x=False
485
+ ).status_code
486
+
487
+ def read_unit_story(self,
488
+ user_id: int,
489
+ story_id: int,
490
+ skip: bool = True,
491
+ num_pages: int = 0) -> int:
492
+ return self._read_story(
493
+ f"api/user/{user_id}/story/unit_story/episode/{story_id}",
494
+ skip,
495
+ num_pages
496
+ )
497
+
498
+ def read_archive_event_story(self,
499
+ user_id: int,
500
+ story_id: int,
501
+ skip: bool = True,
502
+ num_pages: int = 0) -> int:
503
+ return self._read_story(
504
+ f"api/user/{user_id}/story/archive_event_story/episode/{story_id}",
505
+ skip,
506
+ num_pages
507
+ )
508
+ def read_special_story(self,
509
+ user_id: int,
510
+ story_id: int) -> int:
511
+ return self.call(
512
+ "POST",
513
+ f"api/user/{user_id}/story/special_story/episode/{story_id}",
514
+ data=EMPTY
515
+ )
516
+ #endregion
517
+ #region Live Shows
518
+ def start_live_show(self,
519
+ user_id: int,
520
+ song_id: int,
521
+ difficulty_id: int,
522
+ vocal_id: int,
523
+ deck_id: int,
524
+ boost_count: int,
525
+ is_auto: bool,
526
+ music_category_name: str,
527
+ score: int,
528
+ accuracyCount: list[int, int, int, int, int],
529
+ maxCombo: int,
530
+ life: int,
531
+ tapCount: int,
532
+ ingameCutinCharacterArchiveVoiceGroupIds: list[int],
533
+ liveResultCharacterArchiveVoiceGroupId: int) -> int:
534
+ raise NotImplementedError
535
+ #endregion
536
+ #region Virtual Shows
537
+ def attend_virtual_show(self, user_id: int) -> dict:
538
+ # i have no clue how im gonna do this.
539
+ raise NotImplementedError
540
+ #endregion
541
+ #region Events
542
+ def get_event_ranking_raw(self, user_id: int, event_id: int) -> dict:
543
+ return self.call(
544
+ "GET",
545
+ f"api/user/{user_id}/event/{event_id}/ranking?rankingViewType=user_myself"
546
+ )
547
+
548
+ def get_event_participation(self, user_id: int, event_id: int) -> dict:
549
+ user_status = self.get_event_ranking_raw(user_id, event_id).get('userRankingStatus')
550
+ return not (user_status is None or user_status == 'non_participation')
551
+
552
+ def get_event_rank(self, user_id: int, event_id: int) -> int | None:
553
+ rankings = self.get_event_ranking_raw(user_id, event_id).get('rankings')
554
+ if rankings is None: return None
555
+ user_ranking = [rank for rank in rankings if rank.get('userId') == user_id]
556
+ if len(user_ranking) == 0: return None
557
+ return user_ranking[0].get('rank', 0)
558
+
559
+ def get_event_score(self, user_id: int, event_id: int) -> int | None:
560
+ rankings = self.get_event_ranking_raw(user_id, event_id).get('rankings')
561
+ if rankings is None: return None
562
+ user_ranking = [rank for rank in rankings if rank.get('userId') == user_id]
563
+ if len(user_ranking) == 0: return None
564
+ return user_ranking[0].get('score', 0)
565
+
566
+ def exchange_for_event_item(self, user_id: int, item_id: int, count: int) -> dict:
567
+ return self.call(
568
+ "PUT",
569
+ f"api/user/{user_id}/event-exchange/{item_id}?count={count}"
570
+ )
571
+ #endregion
572
+ #region Green Room
573
+ def claim_green_room(self, user_id: int, cards: list[dict]) -> dict:
574
+ assert isinstance(cards, list)
575
+ assert len(cards) != 0
576
+ return self.call(
577
+ "PUT",
578
+ f"api/user/{user_id}/card/?behavior=exchange",
579
+ data={"userCards": cards}
580
+ )
581
+ #endregion
582
+ #region Gachas
583
+ def pull_gacha(self,
584
+ user_id: int,
585
+ gacha_id: int,
586
+ gacha_behavior_id: int,
587
+ use_paid_crystals: bool = False) -> dict:
588
+ raise NotImplementedError
589
+ #endregion
590
+ #region Items / Shops
591
+ def _purchase_item(self, user_id: int, shop_id: int, item_id: int) -> ...:
592
+ return self.call(
593
+ "POST",
594
+ f"api/user/{user_id}/shop/{shop_id}/item/{item_id}",
595
+ data=EMPTY
596
+ )
597
+
598
+ def purchase_costume(self, user_id: int, costume_id: int) -> dict:
599
+ return self.call(
600
+ "POST",
601
+ f"api/user/{user_id}/costume-3d-shop/{costume_id}",
602
+ data=EMPTY
603
+ )
604
+
605
+ def purchase_stamp(self, user_id: int, stamp_id: int) -> dict:
606
+ return self._purchase_item(user_id, 12, stamp_id)
607
+
608
+ def purchase_song(self, user_id: int, song_id: int) -> dict:
609
+ # shop id 2
610
+ raise NotImplementedError
611
+
612
+ def purchase_cover(self, user_id: int, cover_id: int) -> dict:
613
+ # shop id 4
614
+ raise NotImplementedError
615
+
616
+ def purchase_area_item(self, user_id: int, group: int, item_id: int) -> dict:
617
+ raise NotImplementedError
618
+
619
+ #endregion
620
+ #region Other Users
621
+ def search_user(self, other_user_id: int) -> dict:
622
+ """Returns a user's profile info, given by searching for their ID. Contains minimal info."""
623
+ return self.call(
624
+ "GET",
625
+ f"api/user/{other_user_id}/profile"
626
+ )
627
+
628
+ def send_friend_request(self,
629
+ user_id: int,
630
+ other_user_id: int,
631
+ message: str = "Hi there! Nice to meet you!") -> int:
632
+ return self.call(
633
+ "POST",
634
+ f"api/user/{user_id}/friend/{other_user_id}",
635
+ data={'message': message, 'friendRequestSentLocation': 'id_search'}
636
+ )
637
+ #endregion
sekai/constants.py ADDED
@@ -0,0 +1,3 @@
1
+ KEY = b"\xdf8B\x14\xb2\x9a:\xdf\xbf\x1b\xd9\xee[\x16\xf8\x84"
2
+ IV = b"~\x85l\x90y\x87\xf8\xae\xc6\xaf\xc0\xc5G8\xfc~"
3
+ EMPTY = b"\x6c\x4d\x28\x4a\x2d\xb6\xee\x40\xd9\x37\xa0\x0e\x5b\xb8\x0e\x74"
@@ -0,0 +1,2 @@
1
+ from .system_info import SystemInfo
2
+ from .device_info import DeviceInfo
@@ -0,0 +1,8 @@
1
+ from .model import Model
2
+ from uuid import uuid4
3
+
4
+ class DeviceInfo(Model):
5
+ platform = "Android"
6
+ device_model = "LGE Nexus 5"
7
+ operating_system = "Android OS 13 / API-33 (TQ3A.230901.001/2407.40000.4.0)"
8
+ install_id = uuid4()
sekai/models/model.py ADDED
@@ -0,0 +1,12 @@
1
+ import re
2
+
3
+ class Model:
4
+ @staticmethod
5
+ def update(data: dict, cls: type):
6
+ # filter out all non-variables from cls.__dict__
7
+ pairs = dict(filter(lambda x: not x[0].startswith("__") and not callable(x[1]), vars(cls).items()))
8
+ for item in data:
9
+ # replace all instances of an uppercase letter (A) with an underscore followed by the character in lowercase (_a)
10
+ key = re.sub(r'(?<!^)(?=[A-Z])', '_', item).lower()
11
+ if key in pairs:
12
+ setattr(cls, key, data[item])
@@ -0,0 +1,20 @@
1
+ from .model import Model
2
+
3
+ class SystemInfo(Model):
4
+ system_profile = None
5
+ app_version = None
6
+ multi_play_version = None
7
+ data_version = None
8
+ asset_version = None
9
+ app_hash = None
10
+ asset_hash = None
11
+ app_version_status = None
12
+
13
+ @staticmethod
14
+ def update(data: dict) -> None:
15
+ appVersions = data.get("appVersions")
16
+ super(__class__, __class__).update(appVersions[-1], __class__) # what the fuck?
17
+
18
+ @staticmethod
19
+ def direct_update(data: dict) -> None:
20
+ super(__class__, __class__).update(data, __class__)
sekai/py.typed ADDED
File without changes
sekai/utils.py ADDED
@@ -0,0 +1,58 @@
1
+ from Crypto.Cipher import AES
2
+ from Crypto.Util.Padding import pad, unpad
3
+ import msgpack
4
+
5
+ from .constants import KEY, IV
6
+
7
+ def _decrypt(ciphertext: bytes) -> bytes:
8
+ cipher = AES.new(KEY, AES.MODE_CBC, IV)
9
+ plaintext = cipher.decrypt(ciphertext)
10
+ return plaintext
11
+
12
+ def decrypt_and_unpack(ciphertext: bytes) -> dict:
13
+ decrypted = _decrypt(ciphertext)
14
+ try:
15
+ return msgpack.unpackb(decrypted[:-decrypted[-1]],strict_map_key = False)
16
+ except IndexError:
17
+ print(decrypted)
18
+ exit(1)
19
+
20
+ def _encrypt(plaintext: bytes) -> bytes:
21
+ cipher = AES.new(KEY, AES.MODE_CBC, iv=IV)
22
+ ciphertext: bytes = cipher.encrypt(pad(plaintext, 16))
23
+ return ciphertext
24
+
25
+ def encrypt_and_pack(data: dict) -> bytes:
26
+ packed = msgpack.packb(data, use_bin_type = True)
27
+ return _encrypt(packed)
28
+
29
+ def character_from_id(character_id: int) -> str:
30
+ characters_list = [ # found this easier than a match case. so sue me!
31
+ "Hoshino Ichika",
32
+ "Tenma Saki",
33
+ "Mochizuki Honami",
34
+ "Hinomori Shiho",
35
+ "Hanasato Minori",
36
+ "Kiratani Haruka",
37
+ "Momoi Airi",
38
+ "Hinomori Shizuku",
39
+ "Azusawa Kohane",
40
+ "Shiraishi An",
41
+ "Shinonome Akito",
42
+ "Aoyagi Toya",
43
+ "Tenma Tsukasa",
44
+ "Otori Emu",
45
+ "Kusanagi Nene",
46
+ "Kamishiro Rui",
47
+ "Yoisaki Kanade",
48
+ "Asahina Mafuyu",
49
+ "Shinonome Ena",
50
+ "Akiyama Mizuki",
51
+ "Hatsune Miku",
52
+ "Kagamine Rin",
53
+ "Kagamine Len",
54
+ "Megurine Luka",
55
+ "MEIKO",
56
+ "KAITO"
57
+ ]
58
+ return characters_list[character_id - 1]
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: sekai
3
+ Version: 0.1.0
4
+ Summary: A WIP API wrapper for Hatsune Miku: Colorful Stage! global servers.
5
+ Author-email: Taggie <taggie@yip.cat>
6
+ Requires-Python: >=3.13
7
+ Requires-Dist: coloredlogs>=15.0.1
8
+ Requires-Dist: httpx>=0.28.1
9
+ Requires-Dist: jwt>=1.4.0
10
+ Requires-Dist: msgpack>=1.1.2
11
+ Requires-Dist: pycryptodome>=3.23.0
@@ -0,0 +1,13 @@
1
+ sekai/__init__.py,sha256=8AA-6Sg_EXw-JETZGM07ljKhJPcrjnJtX7FalH0ztzs,394
2
+ sekai/constants.py,sha256=A573wY5O2RETUQO81X5BY9_dmuWRwtw4ODFRyh0dgrQ,194
3
+ sekai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ sekai/utils.py,sha256=SYWOTTzRdyD3eJenzwKTdYjaRrTLub1GRfZ5Bu-j5-M,1677
5
+ sekai/api/__init__.py,sha256=2A-nISnvZoaJEl-YV4jlh0HTQqi3g0hbvBopagVFgbE,22
6
+ sekai/api/api.py,sha256=e8dGtu6XQTgYwyZeNe8ET_f2JwUqH6wZMxfXd0zjmnM,24852
7
+ sekai/models/__init__.py,sha256=7lqScKnaBYWoTbp-W3YJ56hC9BU1XbkeUg09n0CCkI0,72
8
+ sekai/models/device_info.py,sha256=LMresdPPWj_KHMbs64vNtF_oJu_k7PChvGJDu0pIgOg,244
9
+ sekai/models/model.py,sha256=z5G9Blj6wqBTIVMdh3DLgDHmD7S-mQgmp4Na2IA-WQI,547
10
+ sekai/models/system_info.py,sha256=jotA9nTCKaQgdzkFKr4uvDIEBpJbS719h1Kpgl1tU6U,584
11
+ sekai-0.1.0.dist-info/METADATA,sha256=rvXCdBmZRdvAyVNnrqypbT-scwqEWBJ0q9sPwY5lfOs,344
12
+ sekai-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
13
+ sekai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any