-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathsku.py
359 lines (287 loc) · 11.8 KB
/
sku.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
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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.
"""
from __future__ import annotations
from typing import AsyncIterator, Optional, TYPE_CHECKING
from datetime import datetime
from . import utils
from .enums import try_enum, SKUType, EntitlementType
from .flags import SKUFlags
from .object import Object
from .subscription import Subscription
if TYPE_CHECKING:
from .abc import SnowflakeTime, Snowflake
from .guild import Guild
from .state import ConnectionState
from .types.sku import (
SKU as SKUPayload,
Entitlement as EntitlementPayload,
)
from .user import User
__all__ = (
'SKU',
'Entitlement',
)
class SKU:
"""Represents a premium offering as a stock-keeping unit (SKU).
.. versionadded:: 2.4
Attributes
-----------
id: :class:`int`
The SKU's ID.
type: :class:`SKUType`
The type of the SKU.
application_id: :class:`int`
The ID of the application that the SKU belongs to.
name: :class:`str`
The consumer-facing name of the premium offering.
slug: :class:`str`
A system-generated URL slug based on the SKU name.
"""
__slots__ = (
'_state',
'id',
'type',
'application_id',
'name',
'slug',
'_flags',
)
def __init__(self, *, state: ConnectionState, data: SKUPayload):
self._state: ConnectionState = state
self.id: int = int(data['id'])
self.type: SKUType = try_enum(SKUType, data['type'])
self.application_id: int = int(data['application_id'])
self.name: str = data['name']
self.slug: str = data['slug']
self._flags: int = data['flags']
def __repr__(self) -> str:
return f'<SKU id={self.id} name={self.name!r} slug={self.slug!r}>'
@property
def flags(self) -> SKUFlags:
""":class:`SKUFlags`: Returns the flags of the SKU."""
return SKUFlags._from_value(self._flags)
@property
def created_at(self) -> datetime:
""":class:`datetime.datetime`: Returns the sku's creation time in UTC."""
return utils.snowflake_time(self.id)
async def fetch_subscription(self, subscription_id: int, /) -> Subscription:
"""|coro|
Retrieves a :class:`.Subscription` with the specified ID.
.. versionadded:: 2.5
Parameters
-----------
subscription_id: :class:`int`
The subscription's ID to fetch from.
Raises
-------
NotFound
An subscription with this ID does not exist.
HTTPException
Fetching the subscription failed.
Returns
--------
:class:`.Subscription`
The subscription you requested.
"""
data = await self._state.http.get_sku_subscription(self.id, subscription_id)
return Subscription(data=data, state=self._state)
async def subscriptions(
self,
*,
limit: Optional[int] = 50,
before: Optional[SnowflakeTime] = None,
after: Optional[SnowflakeTime] = None,
user: Snowflake,
) -> AsyncIterator[Subscription]:
"""Retrieves an :term:`asynchronous iterator` of the :class:`.Subscription` that SKU has.
.. versionadded:: 2.5
Examples
---------
Usage ::
async for subscription in sku.subscriptions(limit=100, user=user):
print(subscription.user_id, subscription.current_period_end)
Flattening into a list ::
subscriptions = [subscription async for subscription in sku.subscriptions(limit=100, user=user)]
# subscriptions is now a list of Subscription...
All parameters are optional.
Parameters
-----------
limit: Optional[:class:`int`]
The number of subscriptions to retrieve. If ``None``, it retrieves every subscription for this SKU.
Note, however, that this would make it a slow operation. Defaults to ``100``.
before: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]]
Retrieve subscriptions before this date or entitlement.
If a datetime is provided, it is recommended to use a UTC aware datetime.
If the datetime is naive, it is assumed to be local time.
after: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]]
Retrieve subscriptions after this date or entitlement.
If a datetime is provided, it is recommended to use a UTC aware datetime.
If the datetime is naive, it is assumed to be local time.
user: :class:`~discord.abc.Snowflake`
The user to filter by.
Raises
-------
HTTPException
Fetching the subscriptions failed.
TypeError
Both ``after`` and ``before`` were provided, as Discord does not
support this type of pagination.
Yields
--------
:class:`.Subscription`
The subscription with the SKU.
"""
if before is not None and after is not None:
raise TypeError('subscriptions pagination does not support both before and after')
# This endpoint paginates in ascending order.
endpoint = self._state.http.list_sku_subscriptions
async def _before_strategy(retrieve: int, before: Optional[Snowflake], limit: Optional[int]):
before_id = before.id if before else None
data = await endpoint(self.id, before=before_id, limit=retrieve, user_id=user.id)
if data:
if limit is not None:
limit -= len(data)
before = Object(id=int(data[0]['id']))
return data, before, limit
async def _after_strategy(retrieve: int, after: Optional[Snowflake], limit: Optional[int]):
after_id = after.id if after else None
data = await endpoint(
self.id,
after=after_id,
limit=retrieve,
user_id=user.id,
)
if data:
if limit is not None:
limit -= len(data)
after = Object(id=int(data[-1]['id']))
return data, after, limit
if isinstance(before, datetime):
before = Object(id=utils.time_snowflake(before, high=False))
if isinstance(after, datetime):
after = Object(id=utils.time_snowflake(after, high=True))
if before:
strategy, state = _before_strategy, before
else:
strategy, state = _after_strategy, after
while True:
retrieve = 100 if limit is None else min(limit, 100)
if retrieve < 1:
return
data, state, limit = await strategy(retrieve, state, limit)
# Terminate loop on next iteration; there's no data left after this
if len(data) < 100:
limit = 0
for e in data:
yield Subscription(data=e, state=self._state)
class Entitlement:
"""Represents an entitlement from user or guild which has been granted access to a premium offering.
.. versionadded:: 2.4
Attributes
-----------
id: :class:`int`
The entitlement's ID.
sku_id: :class:`int`
The ID of the SKU that the entitlement belongs to.
application_id: :class:`int`
The ID of the application that the entitlement belongs to.
user_id: Optional[:class:`int`]
The ID of the user that is granted access to the entitlement.
type: :class:`EntitlementType`
The type of the entitlement.
deleted: :class:`bool`
Whether the entitlement has been deleted.
starts_at: Optional[:class:`datetime.datetime`]
A UTC start date which the entitlement is valid. Not present when using test entitlements.
ends_at: Optional[:class:`datetime.datetime`]
A UTC date which entitlement is no longer valid. Not present when using test entitlements.
guild_id: Optional[:class:`int`]
The ID of the guild that is granted access to the entitlement
consumed: :class:`bool`
For consumable items, whether the entitlement has been consumed.
"""
__slots__ = (
'_state',
'id',
'sku_id',
'application_id',
'user_id',
'type',
'deleted',
'starts_at',
'ends_at',
'guild_id',
'consumed',
)
def __init__(self, state: ConnectionState, data: EntitlementPayload):
self._state: ConnectionState = state
self.id: int = int(data['id'])
self.sku_id: int = int(data['sku_id'])
self.application_id: int = int(data['application_id'])
self.user_id: Optional[int] = utils._get_as_snowflake(data, 'user_id')
self.type: EntitlementType = try_enum(EntitlementType, data['type'])
self.deleted: bool = data['deleted']
self.starts_at: Optional[datetime] = utils.parse_time(data.get('starts_at', None))
self.ends_at: Optional[datetime] = utils.parse_time(data.get('ends_at', None))
self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id')
self.consumed: bool = data.get('consumed', False)
def __repr__(self) -> str:
return f'<Entitlement id={self.id} type={self.type!r} user_id={self.user_id}>'
@property
def user(self) -> Optional[User]:
"""Optional[:class:`User`]: The user that is granted access to the entitlement."""
if self.user_id is None:
return None
return self._state.get_user(self.user_id)
@property
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild that is granted access to the entitlement."""
return self._state._get_guild(self.guild_id)
@property
def created_at(self) -> datetime:
""":class:`datetime.datetime`: Returns the entitlement's creation time in UTC."""
return utils.snowflake_time(self.id)
def is_expired(self) -> bool:
""":class:`bool`: Returns ``True`` if the entitlement is expired. Will be always False for test entitlements."""
if self.ends_at is None:
return False
return utils.utcnow() >= self.ends_at
async def consume(self) -> None:
"""|coro|
Marks a one-time purchase entitlement as consumed.
Raises
-------
NotFound
The entitlement could not be found.
HTTPException
Consuming the entitlement failed.
"""
await self._state.http.consume_entitlement(self.application_id, self.id)
async def delete(self) -> None:
"""|coro|
Deletes the entitlement.
Raises
-------
NotFound
The entitlement could not be found.
HTTPException
Deleting the entitlement failed.
"""
await self._state.http.delete_entitlement(self.application_id, self.id)