-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathuser.py
504 lines (369 loc) · 19.9 KB
/
user.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Generator, Literal, Optional, overload
from typing_extensions import Self
from psnawp_api.core import (
PSNAWPBadRequest,
PSNAWPForbidden,
PSNAWPNotFound,
)
from psnawp_api.models.listing import PaginationArguments
from psnawp_api.models.title_stats import TitleStatsIterator
from psnawp_api.models.trophies import (
TrophyGroupsSummaryBuilder,
TrophyIterator,
TrophySummary,
TrophyTitleIterator,
TrophyWithProgressIterator,
)
from psnawp_api.utils import API_PATH, BASE_PATH, extract_region_from_npid
if TYPE_CHECKING:
from pycountry.db import Country
from psnawp_api.core import Authenticator
from psnawp_api.models.trophies import PlatformType, TrophyGroupsSummary, TrophyGroupSummary, TrophyGroupSummaryWithProgress
class User:
"""This class will contain the information about the PSN ID you passed in when creating object"""
@classmethod
def from_online_id(cls, authenticator: Authenticator, online_id: str) -> Self:
"""Creates the User instance from online ID and returns the instance.
:param authenticator: The Authenticator instance used for making authenticated requests to the API.
:param online_id: Online ID (GamerTag) of the user.
:returns: User Class object which represents a PlayStation account
:raises PSNAWPNotFound: If the user is not valid/found.
"""
try:
query = {"fields": "accountId,onlineId,currentOnlineId"}
response: dict[str, Any] = authenticator.get(
url=f"{BASE_PATH['legacy_profile_uri']}{API_PATH['legacy_profile'].format(online_id=online_id)}",
params=query,
).json()
account_id = response["profile"]["accountId"]
online_id = response["profile"].get("currentOnlineId") or response["profile"].get("onlineId")
return cls(authenticator, online_id, account_id)
except PSNAWPNotFound as not_found:
raise PSNAWPNotFound(f"Online ID {online_id} does not exist.") from not_found
@classmethod
def from_account_id(cls, authenticator: Authenticator, account_id: str) -> Self:
"""Creates the User instance from account ID and returns the instance.
:param request_builder: Used to call http requests.
:param account_id: Account ID of the user.
:returns: User Class object which represents a PlayStation account
:raises PSNAWPNotFound: If the user is not valid/found.
"""
try:
response: dict[str, Any] = authenticator.get(url=f"{BASE_PATH['profile_uri']}{API_PATH['profiles'].format(account_id=account_id)}").json()
return cls(authenticator, response["onlineId"], account_id)
except PSNAWPBadRequest as bad_request:
raise PSNAWPNotFound(f"Account ID {account_id} does not exist.") from bad_request
def __init__(
self,
authenticator: Authenticator,
online_id: str,
account_id: str,
):
"""Constructor of Class User.
:param authenticator: The Authenticator instance used for making authenticated requests to the API.
:param online_id: Online ID (GamerTag) of the user.
:param account_id: Account ID of the user.
.. note::
This class is intended to be interfaced with through PSNAWP.
"""
self.authenticator = authenticator
self.online_id = online_id
self.account_id = account_id
self.prev_online_id = online_id
def profile(self) -> dict[str, Any]:
"""Gets the profile of the user such as about me, avatars, languages etc...
:returns: A dict containing info similar to what is shown below:
.. literalinclude:: examples/user/profile.json
:language: json
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.profile())
"""
response: dict[str, Any] = self.authenticator.get(url=f"{BASE_PATH['profile_uri']}{API_PATH['profiles'].format(account_id=self.account_id)}").json()
return response
def get_region(self) -> Optional[Country]:
"""Gets the region of the user.
:returns: Returns Country object from Pycountry of the User or None if not found.
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.get_region())
.. note::
See https://github.com/pycountry/pycountry for more info on Country object.
"""
response = self.get_profile_legacy()
npid = response.get("profile", {}).get("npId", "")
return extract_region_from_npid(npid)
def get_profile_legacy(self) -> dict[str, Any]:
"""Gets the user profile info from legacy api endpoint. Useful for legacy console (PS3, PS4) presence.
:returns: A dict containing info similar to what is shown below:
.. literalinclude:: examples/client/get_profile_legacy.json
:language: json
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.get_profile_legacy())
"""
params = {
"fields": "npId,onlineId,accountId,avatarUrls,plus,aboutMe,languagesUsed,trophySummary(@default,level,progress,earnedTrophies),"
"isOfficiallyVerified,personalDetail(@default,profilePictureUrls),personalDetailSharing,personalDetailSharingRequestMessageFlag,"
"primaryOnlineStatus,presences(@default,@titleInfo,platform,lastOnlineDate,hasBroadcastData),requestMessageFlag,blocking,friendRelation,"
"following,consoleAvailability"
}
response: dict[str, Any] = self.authenticator.get(
url=f"{BASE_PATH['legacy_profile_uri']}{API_PATH['legacy_profile'].format(online_id=self.online_id)}",
params=params,
).json()
return response
def get_presence(self) -> dict[str, Any]:
"""Gets the presences of a user. If the profile is private
:returns: A dict containing info similar to what is shown below:
.. literalinclude:: examples/user/get_presence.json
:language: json
:raises PSNAWPForbidden: When the user's profile is private, and you don't have permission to view their online status.
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.get_presence())
"""
try:
params = {"type": "primary"}
response: dict[str, Any] = self.authenticator.get(
url=f"{BASE_PATH['profile_uri']}/{self.account_id}{API_PATH['basic_presences']}",
params=params,
).json()
return response
except PSNAWPForbidden as forbidden:
raise PSNAWPForbidden(f"You are not allowed to check the presence of user {self.online_id}") from forbidden
def friendship(self) -> dict[str, Any]:
"""Gets the friendship status and stats of the user
:returns: A dict containing info similar to what is shown below
.. literalinclude:: examples/user/friendship.json
:language: json
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.friendship())
"""
response: dict[Any, Any] = self.authenticator.get(
url=f"{BASE_PATH['profile_uri']}{API_PATH['friends_summary'].format(account_id=self.account_id)}"
).json()
return response
def accept_friend_request(self) -> None:
"""Accept the friend request by the User.
:returns: None
"""
self.authenticator.put(url=f"{BASE_PATH['profile_uri']}{API_PATH['manage_friendship'].format(account_id=self.account_id)}")
def remove_friend(self) -> None:
"""Decline the friend request or unfriend the User.
:returns: None
"""
self.authenticator.delete(url=f"{BASE_PATH['profile_uri']}{API_PATH['manage_friendship'].format(account_id=self.account_id)}")
def friends_list(self, limit: int = 1000) -> Generator[User, None, None]:
"""Gets the friends list and returns an iterator of User objects.
:param limit: The number of items from input max is 1000.
:returns: All friends in your friends list.
:raises PSNAWPForbidden: When the user's when you don't have permission to view their friends list.
.. code-block:: Python
client = psnawp.me()
friends_list = client.friends_list()
for friend in friends_list:
...
"""
limit = min(1000, limit)
params = {"limit": limit}
response = self.authenticator.get(url=f"{BASE_PATH['profile_uri']}{API_PATH['friends_list'].format(account_id=self.account_id)}", params=params).json()
return (
User.from_account_id(
authenticator=self.authenticator,
account_id=account_id,
)
for account_id in response["friends"]
)
def is_blocked(self) -> bool:
"""Checks if the user is blocked by you
:returns: True if the user is blocked otherwise False
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.is_blocked())
"""
response = self.authenticator.get(url=f"{BASE_PATH['profile_uri']}{API_PATH['blocked_users']}").json()
return self.account_id in response["blockList"]
def get_shareable_profile_link(self) -> dict[str, str]:
"""Gets the shareable link and QR code for the PlayStation profile.
This method fetches the URL that can be used to easily share the user's PlayStation profile.
Additionally, it provides a QR code image URL that corresponds to the shareable URL.
:returns: A dict containing info similar to what is shown below:
.. literalinclude:: examples/client/shareable_profile.json
:language: json
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.get_shareable_profile_link())
"""
response: dict[str, str] = self.authenticator.get(url=f"{BASE_PATH['cpss']}{API_PATH['share_profile'].format(account_id=self.account_id)}").json()
return response
def trophy_summary(self) -> TrophySummary:
"""Retrieve an overall summary of the number of trophies earned for a user broken down by
- type
- overall trophy level
- progress towards the next level
- current tier
:returns: Trophy Summary Object containing all information
:raises PSNAWPForbidden: If the user's profile is private
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
print(user_example.trophy_summary())
"""
return TrophySummary.from_endpoint(authenticator=self.authenticator, account_id=self.account_id)
def trophy_titles(self, limit: Optional[int] = None, offset: int = 0, page_size: int = 50) -> TrophyTitleIterator:
"""Retrieve all game titles associated with an account, and a summary of trophies earned from them.
:param limit: Limit of titles returned, None means to return all trophy titles.
:param page_size: The number of items to receive per api request.
:param offset: Specifies the offset for paginator.
:returns: Generator object with TrophyTitle objects.
:raises PSNAWPForbidden: If the user's profile is private.
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
for trophy_title in user_example.trophy_titles(limit=None):
print(trophy_title)
"""
pg_args = PaginationArguments(total_limit=limit, offset=offset, page_size=page_size)
return TrophyTitleIterator.from_endpoint(authenticator=self.authenticator, pagination_args=pg_args, account_id=self.account_id, title_ids=None)
def trophy_titles_for_title(self, title_ids: list[str]) -> TrophyTitleIterator:
"""Retrieve a summary of the trophies earned by a user for specific titles.
:param list[str] title_ids: Unique ID of the title.
:returns: Generator object with TrophyTitle objects.
:raises PSNAWPForbidden: If the user's profile is private.
.. note::
``title_id`` can be obtained from https://andshrew.github.io/PlayStation-Titles/ or from :py:class:`psnawp_api.models.search.Search`
.. code-block:: Python
user_example = psnawp.user(online_id="VaultTec_Trading")
for trophy_title in user_example.trophy_titles_for_title(title_ids=["CUSA00265_00"]):
print(trophy_title)
"""
pg_args = PaginationArguments(total_limit=None, offset=0, page_size=0) # Not used
return TrophyTitleIterator.from_endpoint(authenticator=self.authenticator, pagination_args=pg_args, account_id=self.account_id, title_ids=title_ids)
@overload
def trophies(
self,
np_communication_id: str,
platform: PlatformType,
include_progress: Literal[False] = False,
trophy_group_id: str = "default",
limit: Optional[int] = None,
offset: int = 0,
page_size: int = 200,
) -> TrophyIterator: ...
@overload
def trophies(
self,
np_communication_id: str,
platform: PlatformType,
include_progress: Literal[True],
trophy_group_id: str = "default",
limit: Optional[int] = None,
offset: int = 0,
page_size: int = 200,
) -> TrophyWithProgressIterator: ...
def trophies(
self,
np_communication_id: str,
platform: PlatformType,
include_progress: bool = False,
trophy_group_id: str = "default",
limit: Optional[int] = None,
offset: int = 0,
page_size: int = 200,
) -> TrophyIterator | TrophyWithProgressIterator:
"""Retrieves all trophies for a specified group within a game title, optionally including user progress.
:param np_communication_id: Unique ID of a game title used to request trophy information. This can be obtained from ``GameTitle`` class.
:param platform: The platform this title belongs to.
:param trophy_group_id: ID for the trophy group. Each game expansion is represented by a separate ID. all to return all trophies for the title, default
for the game itself, and additional groups starting from 001 and so on return expansions trophies.
:param limit: Maximum number of trophies to return. None means all available trophies will be returned.
:param include_progress: If True, includes progress information for each trophy.
:param offset: The starting point within the collection of trophies.
:param page_size: The number of trophies to return per page.
:returns: Returns the Trophy Generator object with all the information
:raises PSNAWPNotFound: If you don't have any trophies for that game.
:raises PSNAWPForbidden: If the user's profile is private
.. warning::
Setting ``include_progress`` to ``True`` will consume more rate limits as progress information is fetched from a separate endpoint.
"""
pg_args = PaginationArguments(total_limit=limit, offset=offset, page_size=page_size)
if not include_progress:
return TrophyIterator.from_endpoint(
authenticator=self.authenticator,
pagination_args=pg_args,
np_communication_id=np_communication_id,
platform=platform,
trophy_group_id=trophy_group_id,
)
else:
return TrophyWithProgressIterator.from_endpoint(
authenticator=self.authenticator,
pagination_args=pg_args,
np_communication_id=np_communication_id,
platform=platform,
trophy_group_id=trophy_group_id,
account_id=self.account_id,
)
@overload
def trophy_groups_summary(
self,
np_communication_id: str,
platform: PlatformType,
include_progress: Literal[False] = False,
) -> TrophyGroupsSummary[TrophyGroupSummary]: ...
@overload
def trophy_groups_summary(
self,
np_communication_id: str,
platform: PlatformType,
include_progress: Literal[True],
) -> TrophyGroupsSummary[TrophyGroupSummaryWithProgress]: ...
def trophy_groups_summary(
self,
np_communication_id: str,
platform: PlatformType,
include_progress: bool = False,
) -> TrophyGroupsSummary[TrophyGroupSummary] | TrophyGroupsSummary[TrophyGroupSummaryWithProgress]:
"""Retrieves the trophy groups for a title and their respective trophy count.
This is most commonly seen in games which have expansions where additional trophies are added.
:param np_communication_id: Unique ID of the title used to request trophy information
:param platform: The platform this title belongs to.
:param platform: The platform this title belongs to.
:param include_progress: If True, will fetch results from another endpoint and include progress for trophy group such as name and detail
.. warning::
Setting ``include_progress`` to ``True`` will use twice the amount of rate limit since the API wrapper has to obtain progress from a separate
endpoint.
:returns: TrophyGroupSummary object containing title and title groups trophy information.
:raises PSNAWPNotFound: If you don't have any trophies for that game.
:raises PSNAWPForbidden: If the user's profile is private.
"""
if not include_progress:
return TrophyGroupsSummaryBuilder(
authenticator=self.authenticator,
np_communication_id=np_communication_id,
).game_title_trophy_groups_summary(platform=platform)
else:
return TrophyGroupsSummaryBuilder(
authenticator=self.authenticator,
np_communication_id=np_communication_id,
).earned_user_trophy_groups_summary(account_id=self.account_id, platform=platform)
def title_stats(self, *, limit: Optional[int] = None, offset: int = 0, page_size: int = 200) -> TitleStatsIterator:
"""Retrieve a list of titles with their stats and basic meta-data
:param limit: Limit of titles returned.
:param page_size: The number of items to receive per api request.
:param offset: Specifies the offset for paginator.
.. warning::
Only returns data for PS4 games and above.
:returns: Iterator class for TitleStats
.. code-block:: Python
user_example = psnawp.user(online_id="jeranther")
for title in user_example.title_stats():
...
"""
pg_args = PaginationArguments(total_limit=limit, offset=offset, page_size=page_size)
return TitleStatsIterator.from_endpoint(authenticator=self.authenticator, account_id=self.account_id, pagination_args=pg_args)
def __repr__(self) -> str:
return f"<User online_id:{self.online_id} account_id:{self.account_id}>"
def __str__(self) -> str:
return f"Online ID: {self.online_id} Account ID: {self.account_id}"