forked from smiley/steamapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.py
More file actions
505 lines (439 loc) · 16 KB
/
user.py
File metadata and controls
505 lines (439 loc) · 16 KB
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
505
__author__ = 'SmileyBarry'
from .core import APIConnection, SteamObject, chunker
from .app import SteamApp
from .decorators import cached_property, INFINITE, MINUTE, HOUR
from .errors import *
import datetime
import itertools
class SteamUserBadge(SteamObject):
def __init__(self, badge_id, level, completion_time,
xp, scarcity, appid=None):
"""
Create a new instance of a Steam user badge. You usually shouldn't initialise this object,
but instead receive it from properties like "SteamUser.badges".
:param badge_id: The badge's ID. Not a unique instance ID, but one that helps to identify it
out of a list of user badges. Appears as `badgeid` in the API specification.
:type badge_id: int
:param level: The badge's current level.
:type level: int
:param completion_time: The exact moment when this badge was unlocked. Can either be a
datetime.datetime object or a Unix timestamp.
:type completion_time: int or datetime.datetime
:param xp: This badge's current experience value.
:type xp: int
:param scarcity: How rare this badge is. Expressed as a count of how many people have it.
:type scarcity: int
:param appid: This badge's associated app ID.
:type appid: int
"""
self._badge_id = badge_id
self._level = level
if isinstance(completion_time, datetime.datetime):
self._completion_time = completion_time
else:
self._completion_time = datetime.datetime.fromtimestamp(
completion_time)
self._xp = xp
self._scarcity = scarcity
self._appid = appid
if self._appid is not None:
self._id = self._appid
else:
self._id = self._badge_id
@property
def badge_id(self):
return self._badge_id
@property
def level(self):
return self._level
@property
def xp(self):
return self._xp
@property
def scarcity(self):
return self._scarcity
@property
def appid(self):
return self._appid
@property
def completion_time(self):
return self._completion_time
def __repr__(self):
return '<{clsname} {id} ({xp} XP)>'.format(clsname=self.__class__.__name__,
id=self._id,
xp=self._xp)
def __hash__(self):
# Don't just use the ID so ID collision between different types of
# objects wouldn't cause a match.
return hash((self._appid, self.id))
class SteamGroup(SteamObject):
def __init__(self, guid):
self._id = guid
def __hash__(self):
# Don't just use the ID so ID collision between different types of
# objects wouldn't cause a match.
return hash(('group', self.id))
@property
def guid(self):
return self._id
class SteamUser(SteamObject):
PLAYER_SUMMARIES_BATCH_SIZE = 350
# OVERRIDES
def __init__(self, userid=None, userurl=None, accountid=None):
"""
Create a new instance of a Steam user. Use this object to retrieve details about
that user.
:param userid: The user's 64-bit SteamID. (Optional, unless steam_userurl isn't specified)
:type userid: int
:param userurl: The user's vanity URL-ending name. (Required if "steam_userid" isn't specified,
unused otherwise)
:type userurl: str
:raise: ValueError on improper usage.
"""
if userid is None and userurl is None and accountid is None:
raise ValueError("One of the arguments must be supplied.")
if userurl is not None:
if '/' in userurl:
# This is a full URL. It's not valid.
raise ValueError(
"\"userurl\" must be the *ending* of a vanity URL, not the entire URL!")
response = APIConnection().call(
"ISteamUser", "ResolveVanityURL", "v0001", vanityurl=userurl)
if response.success != 1:
raise UserNotFoundError("User not found.")
userid = response.steamid
if accountid is not None:
userid = self._convert_accountid_to_steamid(accountid)
if userid is not None:
self._id = int(userid)
def __eq__(self, other):
if isinstance(other, SteamUser):
if self.steamid == other.steamid:
return True
else:
return False
else:
return super(SteamUser, self).__eq__(other)
def __str__(self):
return self.name
def __hash__(self):
# Don't just use the ID so ID collision between different types of
# objects wouldn't cause a match.
return hash(('user', self.id))
# PRIVATE UTILITIES
@staticmethod
def _convert_accountid_to_steamid(accountid):
if accountid % 2 == 0:
y = 0
z = accountid / 2
else:
y = 1
z = (accountid - 1) / 2
return "7656119%d" % (z * 2 + 7960265728 + y)
@staticmethod
def _convert_games_list(raw_list, associated_userid=None):
"""
Convert a raw, APIResponse-formatted list of games into full SteamApp objects.
:type raw_list: list of APIResponse
:rtype: list of SteamApp
"""
games_list = []
for game in raw_list:
game_obj = SteamApp.from_api_response(game, associated_userid)
if 'playtime_2weeks' in game:
game_obj.playtime_2weeks = game.playtime_2weeks
if 'playtime_forever' in game:
game_obj.playtime_forever = game.playtime_forever
if 'img_logo_url' in game:
game_obj.img_logo_url = game.img_logo_url
if 'img_icon_url' in game:
game_obj.img_icon_url = game.img_icon_url
games_list += [game_obj]
return games_list
@cached_property(ttl=2 * HOUR)
def _summary(self):
"""
:rtype: APIResponse
"""
return APIConnection().call("ISteamUser", "GetPlayerSummaries",
"v0002", steamids=self.steamid).players[0]
@cached_property(ttl=INFINITE)
def _bans(self):
"""
:rtype: APIResponse
"""
return APIConnection().call("ISteamUser", "GetPlayerBans",
"v1", steamids=self.steamid).players[0]
@cached_property(ttl=30 * MINUTE)
def _badges(self):
"""
:rtype: APIResponse
"""
return APIConnection().call("IPlayerService", "GetBadges", "v1", steamid=self.steamid)
# PUBLIC ATTRIBUTES
@property
def steamid(self):
"""
:rtype: int
"""
return self._id
@cached_property(ttl=INFINITE)
def name(self):
"""
:rtype: str
"""
return self._summary.personaname
@cached_property(ttl=INFINITE)
def real_name(self):
"""
:rtype: str
"""
if "realname" in self._summary:
return self._summary.realname
else:
return None
@cached_property(ttl=INFINITE)
def country_code(self):
"""
:rtype: str or NoneType
"""
return getattr(self._summary, 'loccountrycode', None)
@cached_property(ttl=10 * MINUTE)
def currently_playing(self):
"""
:rtype: SteamApp
"""
if "gameid" in self._summary:
if 'gameextrainfo' in self._summary:
game_name = self._summary.gameextrainfo
else:
game_name = None
game = SteamApp(self._summary.gameid, game_name)
owner = APIConnection().call("IPlayerService", "IsPlayingSharedGame", "v0001",
steamid=self._id,
appid_playing=game.appid)
if owner.lender_steamid != 0:
game._owner = owner.lender_steamid
return game
else:
return None
@property # Already cached by "_summary".
def privacy(self):
"""
:rtype: int or CommunityVisibilityState
"""
# The Web API is a public-facing interface, so it's very unlikely that it will
# ever change drastically. (More values could be added, but existing ones wouldn't
# be changed.)
return self._summary.communityvisibilitystate
@property # Already cached by "_summary".
def last_logoff(self):
"""
:rtype: datetime
"""
return datetime.datetime.fromtimestamp(self._summary.lastlogoff)
@cached_property(ttl=INFINITE) # Already cached, but never changes.
def time_created(self):
"""
:rtype: datetime
"""
return datetime.datetime.fromtimestamp(self._summary.timecreated)
@cached_property(ttl=INFINITE) # Already cached, but unlikely to change.
def profile_url(self):
"""
:rtype: str
"""
return self._summary.profileurl
@property # Already cached by "_summary".
def avatar(self):
"""
:rtype: str
"""
return self._summary.avatar
@property # Already cached by "_summary".
def avatar_medium(self):
"""
:rtype: str
"""
return self._summary.avatarmedium
@property # Already cached by "_summary".
def avatar_full(self):
"""
:rtype: str
"""
return self._summary.avatarfull
@property # Already cached by "_summary".
def state(self):
"""
:rtype: int or OnlineState
"""
return self._summary.personastate
@cached_property(ttl=1 * HOUR)
def groups(self):
"""
:rtype: list of SteamGroup
"""
response = APIConnection().call(
"ISteamUser", "GetUserGroupList", "v1", steamid=self.steamid)
group_list = []
for group in response.groups:
group_obj = SteamGroup(group.gid)
group_list += [group_obj]
return group_list
@cached_property(ttl=1 * HOUR)
def group(self):
"""
:rtype: SteamGroup
"""
return SteamGroup(self._summary.primaryclanid)
@cached_property(ttl=1 * HOUR)
def friends(self):
"""
:rtype: list of SteamUser
"""
import time
response = APIConnection().call("ISteamUser", "GetFriendList", "v0001", steamid=self.steamid,
relationship="friend")
friends_list = []
for friend in response.friendslist.friends:
friend_obj = SteamUser(friend.steamid)
friend_obj.friend_since = friend.friend_since
friend_obj._cache = {}
friends_list += [friend_obj]
# Fetching some details, like name, could take some time.
# So, do a few combined queries for all users.
if APIConnection().precache is True:
# APIConnection() accepts lists of strings as argument values.
id_player_map = {str(friend.steamid): friend for friend in friends_list}
ids = list(id_player_map.keys())
player_details = list(itertools.chain.from_iterable(
APIConnection().call("ISteamUser",
"GetPlayerSummaries",
"v0002",
steamids=id_batch).players
for id_batch in chunker(ids, self.PLAYER_SUMMARIES_BATCH_SIZE)
))
now = time.time()
for player_summary in player_details:
# Fill in the cache with this info.
id_player_map[player_summary.steamid]._cache["_summary"] = (
player_summary, now)
return friends_list
@property # Already cached by "_badges".
def level(self):
"""
:rtype: int
"""
return self._badges.player_level
@property # Already cached by "_badges".
def badges(self):
"""
:rtype: list of SteamUserBadge
"""
badge_list = []
for badge in self._badges.badges:
badge_list += [SteamUserBadge(badge.badgeid,
badge.level,
badge.completion_time,
badge.xp,
badge.scarcity,
getattr(badge, 'appid', None))]
return badge_list
@property # Already cached by "_badges".
def xp(self):
"""
:rtype: int
"""
return self._badges.player_xp
@cached_property(ttl=INFINITE)
def recently_played(self):
"""
:rtype: list of SteamApp
"""
response = APIConnection().call(
"IPlayerService", "GetRecentlyPlayedGames", "v1", steamid=self.steamid)
if 'total_count' not in response:
# Private profiles will cause a special response, where the API doesn't tell us if there are
# any results *at all*. We just get a blank JSON document.
raise AccessException()
if response.total_count == 0:
return []
return self._convert_games_list(response.games, self._id)
@cached_property(ttl=INFINITE)
def games(self):
"""
:rtype: list of SteamApp
"""
response = APIConnection().call("IPlayerService",
"GetOwnedGames",
"v1",
steamid=self.steamid,
include_appinfo=True,
include_played_free_games=True)
if 'game_count' not in response:
# Private profiles will cause a special response, where the API doesn't tell us if there are
# any results *at all*. We just get a blank JSON document.
raise AccessException()
if response.game_count == 0:
return []
return self._convert_games_list(response.games, self._id)
@cached_property(ttl=INFINITE)
def owned_games(self):
"""
:rtype: list of SteamApp
"""
response = APIConnection().call("IPlayerService",
"GetOwnedGames",
"v1",
steamid=self.steamid,
include_appinfo=True,
include_played_free_games=False)
if 'game_count' not in response:
# Private profiles will cause a special response, where the API doesn't tell us if there are
# any results *at all*. We just get a blank JSON document.
raise AccessException()
if response.game_count == 0:
return []
return self._convert_games_list(response.games, self._id)
@cached_property(ttl=INFINITE)
def is_vac_banned(self):
"""
:rtype: bool
"""
return self._bans.VACBanned
@cached_property(ttl=INFINITE)
def is_community_banned(self):
"""
:rtype: bool
"""
return self._bans.CommunityBanned
@cached_property(ttl=INFINITE)
def number_of_vac_bans(self):
"""
:rtype: int
"""
return self._bans.NumberOfVACBans
@cached_property(ttl=INFINITE)
def days_since_last_ban(self):
"""
:rtype: int
"""
return self._bans.DaysSinceLastBan
@cached_property(ttl=INFINITE)
def number_of_game_bans(self):
"""
:rtype: int
"""
return self._bans.NumberOfGameBans
@cached_property(ttl=INFINITE)
def economy_ban(self):
"""
:rtype: str
"""
return self._bans.EconomyBan
@cached_property(ttl=INFINITE)
def is_game_banned(self):
"""
:rtype: bool
"""
return self._bans.NumberOfGameBans != 0