-
Notifications
You must be signed in to change notification settings - Fork 52
/
user.py
478 lines (390 loc) · 16.7 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
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2019-2020 Terbau
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
"""
import logging
from aioxmpp import JID
from typing import TYPE_CHECKING, Any, List, Optional
from .enums import ProfileSearchPlatform, ProfileSearchMatchType
from .typedefs import DatetimeOrTimestamp
if TYPE_CHECKING:
from .client import Client
from .stats import StatsV2
log = logging.getLogger(__name__)
class ExternalAuth:
"""Represents an external auth belonging to a user.
Attributes
----------
client: :class:`Client`
The client.
type: :class:`str`:
The type/platform of the external auth.
id: :class:`str`:
The users universal fortnite id.
external_id: :class:`str`:
The id belonging to this user on the platform.
external_display_name: :class:`str`
The display name belonging to this user on the platform.
extra_info: Dict[:class:`str`, Any]
Extra info from the payload. Usually empty on accounts other
than :class:`ClientUser`.
"""
__slots__ = ('client', 'type', 'id', 'external_id',
'external_display_name', 'extra_info')
def __init__(self, client: 'Client', data: dict) -> None:
self.client = client
self.type = data['type']
self.id = data['accountId']
self.external_id = data['externalAuthId']
self.external_display_name = data['externalDisplayName']
def _update_extra_info(self, data: dict) -> None:
to_be_removed = ('type', 'accountId', 'externalAuthId',
'externalDisplayName')
for field in to_be_removed:
try:
del data[field]
except KeyError:
pass
self.extra_info = data
def __str__(self) -> str:
return self.external_display_name
def __repr__(self) -> str:
return ('<ExternalAuth type={0.type!r} id={0.id!r} '
'external_display_name={0.external_display_name!r} '
'external_id={0.external_id!r}>'.format(self))
def get_raw(self) -> dict:
return {
'type': self.type,
'accountId': self.id,
'externalAuthId': self.external_id,
'externalDisplayName': self.external_display_name,
**self.extra_info
}
class UserBase:
__slots__ = ('client', '_epicgames_display_name', '_external_display_name',
'_id', '_external_auths')
def __init__(self, client: 'Client', data: dict, **kwargs: Any) -> None:
self.client = client
if data:
self._update(data)
def __str__(self) -> str:
return self.display_name
@property
def display_name(self) -> str:
""":class:`str`: The users displayname
.. warning::
The display name will be the one registered to the epicgames
account. If an epicgames account is not found it defaults
to the display name of an external auth.
"""
return self._epicgames_display_name or self._external_display_name
@property
def id(self) -> str:
""":class:`str`: The users id"""
return self._id
@property
def external_auths(self) -> List[ExternalAuth]:
"""List[:class:`ExternalAuth`]: List containing information about
external auths. Might be empty if the user does not have any external
auths.
"""
return self._external_auths
@property
def epicgames_account(self) -> bool:
""":class:`bool`: Tells you if the user is an account registered to epicgames
services. ``False`` if the user is from another platform without
having linked their account to an epicgames account.
.. warning::
If this is True, the display name will be the one registered to
the epicgames account, if not it defaults to the display name of
an external auth.
"""
return self._epicgames_display_name is not None
@property
def jid(self) -> JID:
""":class:`aioxmpp.JID`: The JID of the user."""
return JID.fromstr('{0.id}@{0.client.service_host}'.format(self))
async def fetch_br_stats(self, *,
start_time: Optional[DatetimeOrTimestamp] = None,
end_time: Optional[DatetimeOrTimestamp] = None
) -> 'StatsV2':
"""|coro|
Fetches this users stats.
Parameters
----------
start_time: Optional[Union[:class:`int`, :class:`datetime.datetime`, :class:`SeasonStartTimestamp`]]
The UTC start time of the time period to get stats from.
*Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp*
*Defaults to None*
end_time: Optional[Union[:class:`int`, :class:`datetime.datetime`, :class:`SeasonEndTimestamp`]]
The UTC end time of the time period to get stats from.
*Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp*
*Defaults to None*
Raises
------
Forbidden
| The user has chosen to be hidden from public stats by disabling
the fortnite setting below.
| ``Settings`` -> ``Account and Privacy`` -> ``Show on career
leaderboard``
HTTPException
An error occured while requesting.
Returns
-------
:class:`StatsV2`
An object representing the stats for this user.
""" # noqa
return await self.client.fetch_br_stats(
self.id,
start_time=start_time,
end_time=end_time
)
async def fetch_battlepass_level(self, *,
start_time: Optional[DatetimeOrTimestamp] = None, # noqa
end_time: Optional[DatetimeOrTimestamp] = None # noqa
) -> float:
"""|coro|
Fetches this users battlepass level.
Parameters
----------
start_time: Optional[Union[:class:`int`, :class:`datetime.datetime`, :class:`SeasonStartTimestamp`]]
The UTC start time of the window to get the battlepass level from.
*Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp*
*Defaults to None*
end_time: Optional[Union[:class:`int`, :class:`datetime.datetime`, :class:`SeasonEndTimestamp`]]
The UTC end time of the window to get the battlepass level from.
*Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp*
*Defaults to None*
.. note::
If neither start_time nor end_time is ``None`` (default), then
the battlepass level from the current season is fetched.
Raises
------
HTTPException
An error occured while requesting.
Returns
-------
:class:`float`
The users battlepass level. ``None`` is returned if the user has
not played any real matches this season.
""" # noqa
return await self.client.fetch_battlepass_level(
self.id,
start_time=start_time,
end_time=end_time
)
def _update(self, data: dict) -> None:
self._epicgames_display_name = data.get('displayName',
data.get('account_dn'))
self._update_external_auths(
data.get('externalAuths', data.get('external_auths', [])),
extra_external_auths=data.get('extraExternalAuths', []),
)
self._id = data.get('accountId',
data.get('id', data.get('account_id')))
def _update_external_auths(self, external_auths: List[dict], *,
extra_external_auths: List[dict] = []) -> None:
extra_ext = {v['authIds'][0]['type'].split('_')[0].lower(): v
for v in extra_external_auths}
ext_list = []
for e in external_auths:
ext = ExternalAuth(self.client, e)
ext._update_extra_info(extra_ext.get(ext.type, {}))
ext_list.append(ext)
self._external_display_name = None
for ext_auth in reversed([x for x in ext_list
if x.type.lower() not in ('twitch',)]):
self._external_display_name = ext_auth.external_display_name
break
self._external_auths = ext_list
def _update_epicgames_display_name(self, display_name: str) -> None:
self._epicgames_display_name = display_name
def get_raw(self) -> dict:
return {
'displayName': self.display_name,
'id': self.id,
'externalAuths': [ext.get_raw() for ext in self._external_auths]
}
class ClientUser(UserBase):
"""Represents the user the client is connected to.
Attributes
----------
client: :class:`Client`
The client.
age_group: :class:`str`
The age group of the user.
can_update_display_name: :class:`bool`
``True`` if the user can update it's displayname else ``False``
country: :class:`str`
The country the user wasregistered in.
email: :class:`str`
The email of the user.
failed_login_attempts: :class:`str`
Failed login attempts
headless: :class:`bool`
``True`` if the account has no display name due to no epicgames
account being linked to the current account.
last_login: :class:`datetime.datetime`
UTC time of the last login of the user. ``None`` if no failed login
attempt has been registered.
name: :class:`str`
First name of the user.
first_name: :class:`str`
First name of the user. Alias for name.
last_name: :class:`str`
Last name of the user.
full_name: :class:`str`
Full name of the user.
number_of_display_name_changes: :class:`int`
Amount of displayname changes.
preferred_language: :class:`str`
Users preferred language.
tfa_enabled: :class:`bool`
``True`` if the user has two-factor authentication enabled else
``False``.
email_verified: :class:`bool`
``True`` if the accounts email has been verified.
minor_verified: :class:`bool`
``True`` if the account has been verified to be run by a minor.
minor_expected: :class:`bool`
``True`` if the account is expected to be run by a minor.
minor_status: :class:`str`
The minor status of this account.
"""
def __init__(self, client: 'Client', data: dict, **kwargs: Any) -> None:
super().__init__(client, data)
self._update(data)
def __repr__(self) -> str:
return ('<ClientUser id={0.id!r} display_name={0.display_name!r} '
'jid={0.jid!r} email={0.email!r}>'.format(self))
@property
def first_name(self) -> str:
return self.name
@property
def full_name(self) -> str:
return '{} {}'.format(self.name, self.last_name)
@property
def jid(self) -> JID:
""":class:`aioxmpp.JID`: The JID of the client. Includes the
resource part.
"""
return self.client.xmpp.xmpp_client.local_jid
def _update(self, data: dict) -> None:
super()._update(data)
self.name = data['name']
self.email = data['email']
self.failed_login_attempts = data['failedLoginAttempts']
self.last_failed_login = (self.client.from_iso(data['lastFailedLogin'])
if 'lastFailedLogin' in data else None)
self.last_login = (self.client.from_iso(data['lastLogin'])
if 'lastLogin' in data else None)
n_changes = data['numberOfDisplayNameChanges']
self.number_of_display_name_changes = n_changes
self.age_group = data['ageGroup']
self.headless = data['headless']
self.country = data['country']
self.last_name = data['lastName']
self.preferred_language = data['preferredLanguage']
self.can_update_display_name = data['canUpdateDisplayName']
self.tfa_enabled = data['tfaEnabled']
self.email_verified = data['emailVerified']
self.minor_verified = data['minorVerified']
self.minor_expected = data['minorExpected']
self.minor_status = data['minorStatus']
class User(UserBase):
"""Represents a user from Fortnite"""
__slots__ = UserBase.__slots__
def __init__(self, client: 'Client', data: dict, **kwargs: Any) -> None:
super().__init__(client, data)
def __repr__(self) -> str:
return ('<User id={0.id!r} display_name={0.display_name!r} '
'epicgames_account={0.epicgames_account!r}>'.format(self))
async def block(self) -> None:
"""|coro|
Blocks this user.
Raises
------
HTTPException
Something went wrong while blocking this user.
"""
await self.client.block_user(self.id)
class BlockedUser(UserBase):
"""Represents a blocked user from Fortnite"""
__slots__ = UserBase.__slots__
def __init__(self, client: 'Client', data: dict) -> None:
super().__init__(client, data)
def __repr__(self) -> str:
return ('<BlockedUser id={0.id!r} '
'display_name={0.display_name!r} '
'epicgames_account={0.epicgames_account!r}>'.format(self))
async def unblock(self) -> None:
"""|coro|
Unblocks this friend.
"""
await self.client.unblock_user(self.id)
class ProfileSearchEntryUser(User):
"""Represents a user entry in a profile search.
Parameters
----------
matches: List[Tuple[:class:`str`, :class:`ProfileSearchPlatform`]]
| A list of tuples containing the display name the user matched
and the platform the display name is from.
| Example: ``[('Tfue', ProfileSearchPlatform.EPIC_GAMES)]``
match_type: :class:`ProfileSearchMatchType`
The type of match this user matched by.
mutual_friend_count: :class:`int`
The amount of **epic** mutual friends the client has with the user.
"""
def __init__(self, client: 'Client',
profile_data: dict,
search_data: dict) -> None:
super().__init__(client, profile_data)
self.matches = [(d['value'], ProfileSearchPlatform(d['platform']))
for d in search_data['matches']]
self.match_type = ProfileSearchMatchType(search_data['matchType'])
self.mutual_friend_count = search_data['epicMutuals']
def __str__(self) -> str:
return self.matches[0][0]
def __repr__(self) -> str:
return ('<ProfileSearchEntryUser id={0.id!r} '
'display_name={0.display_name!r} '
'epicgames_account={0.epicgames_account!r}>'.format(self))
class SacSearchEntryUser(User):
"""Represents a user entry in a support a creator code search.
Parameters
----------
slug: :class:`str`
The slug (creator code) that matched.
active: :class:`bool`
Wether or not the creator code is active or not.
verified: :class:`bool`
Wether or not the creator code is verified or not.
"""
def __init__(self, client: 'Client',
profile_data: dict,
search_data: dict) -> None:
super().__init__(client, profile_data)
self.slug = search_data['slug']
self.active = search_data['status'] == 'ACTIVE'
self.verified = search_data['verified']
def __repr__(self) -> str:
return ('<SacSearchEntryUser slug={0.slug!r} '
'id={0.id!r} '
'display_name={0.display_name!r} '
'epicgames_account={0.epicgames_account!r}>'.format(self))