/
collections.py
588 lines (411 loc) · 17.5 KB
/
collections.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
"""Provide Collections functionality."""
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Union
from ...const import API_PATH
from ...exceptions import ClientException
from ...util.cache import cachedproperty
from ..base import PRAWBase
from .base import RedditBase
from .submission import Submission
from .subreddit import Subreddit
if TYPE_CHECKING: # pragma: no cover
import praw
class CollectionModeration(PRAWBase):
"""Class to support moderation actions on a :class:`.Collection`.
Obtain an instance via:
.. code-block:: python
reddit.subreddit("test").collections("some_uuid").mod
"""
def _post_fullname(self, post):
"""Get a post's fullname.
:param post: A fullname, a :class:`.Submission`, a permalink, or an ID.
:returns: The fullname of the post.
"""
if isinstance(post, Submission):
return post.fullname
elif not isinstance(post, str):
raise TypeError(f"Cannot get fullname from object of type {type(post)}.")
if post.startswith(f"{self._reddit.config.kinds['submission']}_"):
return post
try:
return self._reddit.submission(url=post).fullname
except ClientException:
return self._reddit.submission(post).fullname
def __init__(self, reddit: "praw.Reddit", collection_id: str):
"""Initialize a :class:`.CollectionModeration` instance.
:param collection_id: The ID of a :class:`.Collection`.
"""
super().__init__(reddit, _data=None)
self.collection_id = collection_id
def add_post(self, submission: "praw.models.Submission"):
"""Add a post to the collection.
:param submission: The post to add, a :class:`.Submission`, its permalink as a
``str``, its fullname as a ``str``, or its ID as a ``str``.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
collection.mod.add_post("bgibu9")
.. seealso::
:meth:`.remove_post`
"""
link_fullname = self._post_fullname(submission)
self._reddit.post(
API_PATH["collection_add_post"],
data={"collection_id": self.collection_id, "link_fullname": link_fullname},
)
def delete(self):
"""Delete this collection.
Example usage:
.. code-block:: python
reddit.subreddit("test").collections("some_uuid").mod.delete()
.. seealso::
:meth:`~.SubredditCollectionsModeration.create`
"""
self._reddit.post(
API_PATH["collection_delete"],
data={"collection_id": self.collection_id},
)
def remove_post(self, submission: "praw.models.Submission"):
"""Remove a post from the collection.
:param submission: The post to remove, a :class:`.Submission`, its permalink as
a ``str``, its fullname as a ``str``, or its ID as a ``str``.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
collection.mod.remove_post("bgibu9")
.. seealso::
:meth:`.add_post`
"""
link_fullname = self._post_fullname(submission)
self._reddit.post(
API_PATH["collection_remove_post"],
data={"collection_id": self.collection_id, "link_fullname": link_fullname},
)
def reorder(self, links: List[Union[str, "praw.models.Submission"]]):
r"""Reorder posts in the collection.
:param links: A list of :class:`.Submission`\ s or a ``str`` that is either a
fullname or an ID.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
current_order = collection.link_ids
new_order = reversed(current_order)
collection.mod.reorder(new_order)
"""
link_ids = ",".join(self._post_fullname(post) for post in links)
self._reddit.post(
API_PATH["collection_reorder"],
data={"collection_id": self.collection_id, "link_ids": link_ids},
)
def update_description(self, description: str):
"""Update the collection's description.
:param description: The new description.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
collection.mod.update_description("Please enjoy these links!")
.. seealso::
:meth:`.update_title`
"""
self._reddit.post(
API_PATH["collection_desc"],
data={"collection_id": self.collection_id, "description": description},
)
def update_display_layout(self, display_layout: str):
"""Update the collection's display layout.
:param display_layout: Either ``"TIMELINE"`` for events or discussions or
``"GALLERY"`` for images or memes. Passing ``""`` or ``None`` will clear the
set layout and ``collection.display_layout`` will be ``None``, however, the
collection will appear on Reddit as if ``display_layout`` is set to
``"TIMELINE"``.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
collection.mod.update_display_layout("GALLERY")
"""
self._reddit.post(
API_PATH["collection_layout"],
data={
"collection_id": self.collection_id,
"display_layout": display_layout,
},
)
def update_title(self, title: str):
"""Update the collection's title.
:param title: The new title.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
collection.mod.update_title("Titley McTitleface")
.. seealso::
:meth:`.update_description`
"""
self._reddit.post(
API_PATH["collection_title"],
data={"collection_id": self.collection_id, "title": title},
)
class Collection(RedditBase):
"""Class to represent a :class:`.Collection`.
Obtain an instance via:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
or
.. code-block:: python
collection = reddit.subreddit("test").collections(
permalink="https://reddit.com/r/SUBREDDIT/collection/some_uuid"
)
.. include:: ../../typical_attributes.rst
=================== =============================================================
Attribute Description
=================== =============================================================
``author`` The :class:`.Redditor` who created the collection.
``collection_id`` The UUID of the collection.
``created_at_utc`` Time the collection was created, represented in `Unix Time`_.
``description`` The collection description.
``display_layout`` The collection display layout.
``last_update_utc`` Time the collection was last updated, represented in `Unix
Time`_.
``link_ids`` A list of :class:`.Submission` fullnames.
``permalink`` The collection's permalink (to view on the web).
``sorted_links`` An iterable listing of the posts in this collection.
``title`` The title of the collection.
=================== =============================================================
.. _unix time: https://en.wikipedia.org/wiki/Unix_time
"""
STR_FIELD = "collection_id"
@cachedproperty
def mod(self) -> CollectionModeration:
"""Get an instance of :class:`.CollectionModeration`.
Provides access to various methods, including
:meth:`~.CollectionModeration.add_post`, :meth:`~.CollectionModeration.delete`,
:meth:`~.CollectionModeration.reorder`, and
:meth:`~.CollectionModeration.update_title`.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
collection.mod.update_title("My new title!")
"""
return CollectionModeration(self._reddit, self.collection_id)
@cachedproperty
def subreddit(self) -> "praw.models.Subreddit":
"""Get the subreddit that this collection belongs to.
For example:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
subreddit = collection.subreddit
"""
return next(self._reddit.info([self.subreddit_id]))
def __init__(
self,
reddit: "praw.Reddit",
_data: Dict[str, Any] = None,
collection_id: Optional[str] = None,
permalink: Optional[str] = None,
):
"""Initialize a :class:`.Collection` instance.
:param reddit: An instance of :class:`.Reddit`.
:param _data: Any data associated with the :class:`.Collection`.
:param collection_id: The ID of the :class:`.Collection`.
:param permalink: The permalink of the :class:`.Collection`.
"""
if (_data, collection_id, permalink).count(None) != 2:
raise TypeError(
"Exactly one of _data, collection_id, or permalink must be provided."
)
if permalink:
collection_id = self._url_parts(permalink)[4]
if collection_id:
self.collection_id = collection_id # set from _data otherwise
super().__init__(reddit, _data)
self._info_params = {
"collection_id": self.collection_id,
"include_links": True,
}
def __iter__(self) -> Generator[Any, None, None]:
"""Provide a way to iterate over the posts in this :class:`.Collection`.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
for submission in collection:
print(submission.title, submission.permalink)
"""
for item in self.sorted_links:
yield item
def __len__(self) -> int:
"""Get the number of posts in this :class:`.Collection`.
Example usage:
.. code-block:: python
collection = reddit.subreddit("test").collections("some_uuid")
print(len(collection))
"""
return len(self.link_ids)
def __setattr__(self, attribute: str, value: Any):
"""Objectify author, subreddit, and sorted_links attributes."""
if attribute == "author_name":
self.author = self._reddit.redditor(value)
elif attribute == "sorted_links":
value = self._reddit._objector.objectify(value)
super().__setattr__(attribute, value)
def _fetch_info(self):
return "collection", {}, self._info_params
def _fetch_data(self):
name, fields, params = self._fetch_info()
path = API_PATH[name].format(**fields)
return self._reddit.request("GET", path, params)
def _fetch(self):
data = self._fetch_data()
try:
self._reddit._objector.check_error(data)
except ClientException:
# A well-formed but invalid Collections ID during fetch time
# causes Reddit to return something that looks like an error
# but with no content.
raise ClientException(
f"Error during fetch. Check collection ID {self.collection_id!r} is"
" correct."
)
other = type(self)(self._reddit, _data=data)
self.__dict__.update(other.__dict__)
self._fetched = True
def follow(self):
"""Follow this :class:`.Collection`.
Example usage:
.. code-block:: python
reddit.subreddit("test").collections("some_uuid").follow()
.. seealso::
:meth:`.unfollow`
"""
self._reddit.post(
API_PATH["collection_follow"],
data={"collection_id": self.collection_id, "follow": True},
)
def unfollow(self):
"""Unfollow this :class:`.Collection`.
Example usage:
.. code-block:: python
reddit.subreddit("test").collections("some_uuid").unfollow()
.. seealso::
:meth:`.follow`
"""
self._reddit.post(
API_PATH["collection_follow"],
data={"collection_id": self.collection_id, "follow": False},
)
class SubredditCollectionsModeration(PRAWBase):
r"""Class to represent moderator actions on a :class:`.Subreddit`'s :class:`.Collection`\ s.
Obtain an instance via:
.. code-block:: python
reddit.subreddit("test").collections.mod
"""
def __init__(
self,
reddit: "praw.Reddit",
sub_fullname: str,
_data: Optional[Dict[str, Any]] = None,
):
"""Initialize a :class:`.SubredditCollectionsModeration` instance."""
super().__init__(reddit, _data)
self.subreddit_fullname = sub_fullname
def create(
self, title: str, description: str, display_layout: Optional[str] = None
):
"""Create a new :class:`.Collection`.
The authenticated account must have appropriate moderator permissions in the
subreddit this collection belongs to.
:param title: The title of the collection, up to 300 characters.
:param description: The description, up to 500 characters.
:param display_layout: Either ``"TIMELINE"`` for events or discussions or
``"GALLERY"`` for images or memes. ``None`` will make the collection appear
on Reddit as if this is set to ``"TIMELINE"`` (default:``None``).
:returns: The newly created :class:`.Collection`.
Example usage:
.. code-block:: python
my_sub = reddit.subreddit("test")
new_collection = my_sub.collections.mod.create("Title", "desc")
new_collection.mod.add_post("bgibu9")
Example usage (specifying display_layout):
.. code-block:: python
my_sub = reddit.subreddit("test")
new_collection = my_sub.collections.mod.create("Title", "desc", "GALLERY")
new_collection.mod.add_post("cmdfe8")
.. seealso::
:meth:`~.CollectionModeration.delete`
"""
API_PATH["collection_create"],
data = {
"sr_fullname": self.subreddit_fullname,
"title": title,
"description": description,
}
if display_layout:
data["display_layout"] = display_layout
return self._reddit.post(
API_PATH["collection_create"],
data=data,
)
class SubredditCollections(PRAWBase):
r"""Class to represent a :class:`.Subreddit`'s :class:`.Collection`\ s.
Obtain an instance via:
.. code-block:: python
reddit.subreddit("test").collections
"""
@cachedproperty
def mod(self) -> SubredditCollectionsModeration:
"""Get an instance of :class:`.SubredditCollectionsModeration`.
Provides :meth:`~SubredditCollectionsModeration.create`:
.. code-block:: python
my_sub = reddit.subreddit("test")
new_collection = my_sub.collections.mod.create("Title", "desc")
"""
return SubredditCollectionsModeration(self._reddit, self.subreddit.fullname)
def __call__(
self,
collection_id: Optional[str] = None,
permalink: Optional[str] = None,
):
"""Return the :class:`.Collection` with the specified ID.
:param collection_id: The ID of a :class:`.Collection` (default: ``None``).
:param permalink: The permalink of a collection (default: ``None``).
:returns: The specified :class:`.Collection`.
Exactly one of ``collection_id`` or ``permalink`` is required.
Example usage:
.. code-block:: python
subreddit = reddit.subreddit("test")
uuid = "847e4548-a3b5-4ad7-afb4-edbfc2ed0a6b"
collection = subreddit.collections(uuid)
print(collection.title)
print(collection.description)
permalink = "https://www.reddit.com/r/SUBREDDIT/collection/" + uuid
collection = subreddit.collections(permalink=permalink)
print(collection.title)
print(collection.description)
"""
if (collection_id is None) == (permalink is None):
raise TypeError(
"Exactly one of collection_id or permalink must be provided."
)
return Collection(
self._reddit, collection_id=collection_id, permalink=permalink
)
def __init__(
self,
reddit: "praw.Reddit",
subreddit: "praw.models.Subreddit",
_data: Optional[Dict[str, Any]] = None,
):
"""Initialize a :class:`.SubredditCollections` instance."""
super().__init__(reddit, _data)
self.subreddit = subreddit
def __iter__(self):
r"""Iterate over the :class:`.Subreddit`'s :class:`.Collection`\ s.
Example usage:
.. code-block:: python
for collection in reddit.subreddit("test").collections:
print(collection.permalink)
"""
request = self._reddit.get(
API_PATH["collection_subreddit"],
params={"sr_fullname": self.subreddit.fullname},
)
for collection in request:
yield collection
Subreddit._subreddit_collections_class = SubredditCollections