]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/patreon.py
fix motherless
[yt-dlp.git] / yt_dlp / extractor / patreon.py
1 import itertools
2 import urllib.parse
3
4 from .common import InfoExtractor
5 from .sproutvideo import VidsIoIE
6 from .vimeo import VimeoIE
7 from ..networking.exceptions import HTTPError
8 from ..utils import (
9 KNOWN_EXTENSIONS,
10 ExtractorError,
11 clean_html,
12 determine_ext,
13 int_or_none,
14 mimetype2ext,
15 parse_iso8601,
16 smuggle_url,
17 str_or_none,
18 traverse_obj,
19 url_or_none,
20 urljoin,
21 )
22
23
24 class PatreonBaseIE(InfoExtractor):
25 USER_AGENT = 'Patreon/7.6.28 (Android; Android 11; Scale/2.10)'
26
27 def _call_api(self, ep, item_id, query=None, headers=None, fatal=True, note=None):
28 if headers is None:
29 headers = {}
30 if 'User-Agent' not in headers:
31 headers['User-Agent'] = self.USER_AGENT
32 if query:
33 query.update({'json-api-version': 1.0})
34
35 try:
36 return self._download_json(
37 f'https://www.patreon.com/api/{ep}',
38 item_id, note=note if note else 'Downloading API JSON',
39 query=query, fatal=fatal, headers=headers)
40 except ExtractorError as e:
41 if not isinstance(e.cause, HTTPError) or mimetype2ext(e.cause.response.headers.get('Content-Type')) != 'json':
42 raise
43 err_json = self._parse_json(self._webpage_read_content(e.cause.response, None, item_id), item_id, fatal=False)
44 err_message = traverse_obj(err_json, ('errors', ..., 'detail'), get_all=False)
45 if err_message:
46 raise ExtractorError(f'Patreon said: {err_message}', expected=True)
47 raise
48
49
50 class PatreonIE(PatreonBaseIE):
51 _VALID_URL = r'https?://(?:www\.)?patreon\.com/(?:creation\?hid=|posts/(?:[\w-]+-)?)(?P<id>\d+)'
52 _TESTS = [{
53 'url': 'http://www.patreon.com/creation?hid=743933',
54 'md5': 'e25505eec1053a6e6813b8ed369875cc',
55 'info_dict': {
56 'id': '743933',
57 'ext': 'mp3',
58 'title': 'Episode 166: David Smalley of Dogma Debate',
59 'description': 'md5:34d207dd29aa90e24f1b3f58841b81c7',
60 'uploader': 'Cognitive Dissonance Podcast',
61 'thumbnail': 're:^https?://.*$',
62 'timestamp': 1406473987,
63 'upload_date': '20140727',
64 'uploader_id': '87145',
65 'like_count': int,
66 'comment_count': int,
67 'uploader_url': 'https://www.patreon.com/dissonancepod',
68 'channel_id': '80642',
69 'channel_url': 'https://www.patreon.com/dissonancepod',
70 'channel_follower_count': int,
71 },
72 }, {
73 'url': 'http://www.patreon.com/creation?hid=754133',
74 'md5': '3eb09345bf44bf60451b8b0b81759d0a',
75 'info_dict': {
76 'id': '754133',
77 'ext': 'mp3',
78 'title': 'CD 167 Extra',
79 'uploader': 'Cognitive Dissonance Podcast',
80 'thumbnail': 're:^https?://.*$',
81 'like_count': int,
82 'comment_count': int,
83 'uploader_url': 'https://www.patreon.com/dissonancepod',
84 },
85 'skip': 'Patron-only content',
86 }, {
87 'url': 'https://www.patreon.com/creation?hid=1682498',
88 'info_dict': {
89 'id': 'SU4fj_aEMVw',
90 'ext': 'mp4',
91 'title': 'I\'m on Patreon!',
92 'uploader': 'TraciJHines',
93 'thumbnail': 're:^https?://.*$',
94 'upload_date': '20150211',
95 'description': 'md5:8af6425f50bd46fbf29f3db0fc3a8364',
96 'uploader_id': '@TraciHinesMusic',
97 'categories': ['Entertainment'],
98 'duration': 282,
99 'view_count': int,
100 'tags': 'count:39',
101 'age_limit': 0,
102 'channel': 'TraciJHines',
103 'channel_url': 'https://www.youtube.com/channel/UCGLim4T2loE5rwCMdpCIPVg',
104 'live_status': 'not_live',
105 'like_count': int,
106 'channel_id': 'UCGLim4T2loE5rwCMdpCIPVg',
107 'availability': 'public',
108 'channel_follower_count': int,
109 'playable_in_embed': True,
110 'uploader_url': 'https://www.youtube.com/@TraciHinesMusic',
111 'comment_count': int,
112 'channel_is_verified': True,
113 'chapters': 'count:4',
114 },
115 'params': {
116 'noplaylist': True,
117 'skip_download': True,
118 },
119 }, {
120 'url': 'https://www.patreon.com/posts/episode-166-of-743933',
121 'only_matching': True,
122 }, {
123 'url': 'https://www.patreon.com/posts/743933',
124 'only_matching': True,
125 }, {
126 'url': 'https://www.patreon.com/posts/kitchen-as-seen-51706779',
127 'md5': '96656690071f6d64895866008484251b',
128 'info_dict': {
129 'id': '555089736',
130 'ext': 'mp4',
131 'title': 'KITCHEN AS SEEN ON DEEZ NUTS EXTENDED!',
132 'uploader': 'Cold Ones',
133 'thumbnail': 're:^https?://.*$',
134 'upload_date': '20210526',
135 'description': 'md5:557a409bd79d3898689419094934ba79',
136 'uploader_id': '14936315',
137 },
138 'skip': 'Patron-only content',
139 }, {
140 # m3u8 video (https://github.com/yt-dlp/yt-dlp/issues/2277)
141 'url': 'https://www.patreon.com/posts/video-sketchbook-32452882',
142 'info_dict': {
143 'id': '32452882',
144 'ext': 'mp4',
145 'comment_count': int,
146 'uploader_id': '4301314',
147 'like_count': int,
148 'timestamp': 1576696962,
149 'upload_date': '20191218',
150 'thumbnail': r're:^https?://.*$',
151 'uploader_url': 'https://www.patreon.com/loish',
152 'description': 'md5:e2693e97ee299c8ece47ffdb67e7d9d2',
153 'title': 'VIDEO // sketchbook flipthrough',
154 'uploader': 'Loish ',
155 'tags': ['sketchbook', 'video'],
156 'channel_id': '1641751',
157 'channel_url': 'https://www.patreon.com/loish',
158 'channel_follower_count': int,
159 },
160 }, {
161 # bad videos under media (if media is included). Real one is under post_file
162 'url': 'https://www.patreon.com/posts/premium-access-70282931',
163 'info_dict': {
164 'id': '70282931',
165 'ext': 'mp4',
166 'title': '[Premium Access + Uncut] The Office - 2x6 The Fight - Group Reaction',
167 'channel_url': 'https://www.patreon.com/thenormies',
168 'channel_id': '573397',
169 'uploader_id': '2929435',
170 'uploader': 'The Normies',
171 'description': 'md5:79c9fd8778e2cef84049a94c058a5e23',
172 'comment_count': int,
173 'upload_date': '20220809',
174 'thumbnail': r're:^https?://.*$',
175 'channel_follower_count': int,
176 'like_count': int,
177 'timestamp': 1660052820,
178 'tags': ['The Office', 'early access', 'uncut'],
179 'uploader_url': 'https://www.patreon.com/thenormies',
180 },
181 'skip': 'Patron-only content',
182 }, {
183 # dead vimeo and embed URLs, need to extract post_file
184 'url': 'https://www.patreon.com/posts/hunter-x-hunter-34007913',
185 'info_dict': {
186 'id': '34007913',
187 'ext': 'mp4',
188 'title': 'Hunter x Hunter | Kurapika DESTROYS Uvogin!!!',
189 'like_count': int,
190 'uploader': 'YaBoyRoshi',
191 'timestamp': 1581636833,
192 'channel_url': 'https://www.patreon.com/yaboyroshi',
193 'thumbnail': r're:^https?://.*$',
194 'tags': ['Hunter x Hunter'],
195 'uploader_id': '14264111',
196 'comment_count': int,
197 'channel_follower_count': int,
198 'description': 'Kurapika is a walking cheat code!',
199 'upload_date': '20200213',
200 'channel_id': '2147162',
201 'uploader_url': 'https://www.patreon.com/yaboyroshi',
202 },
203 }, {
204 # NSFW vimeo embed URL
205 'url': 'https://www.patreon.com/posts/4k-spiderman-4k-96414599',
206 'info_dict': {
207 'id': '902250943',
208 'ext': 'mp4',
209 'title': '❤️(4K) Spiderman Girl Yeonhwa’s Gift ❤️(4K) 스파이더맨걸 연화의 선물',
210 'description': '❤️(4K) Spiderman Girl Yeonhwa’s Gift \n❤️(4K) 스파이더맨걸 연화의 선물',
211 'uploader': 'Npickyeonhwa',
212 'uploader_id': '90574422',
213 'uploader_url': 'https://www.patreon.com/Yeonhwa726',
214 'channel_id': '10237902',
215 'channel_url': 'https://www.patreon.com/Yeonhwa726',
216 'duration': 70,
217 'timestamp': 1705150153,
218 'upload_date': '20240113',
219 'comment_count': int,
220 'like_count': int,
221 'thumbnail': r're:^https?://.+',
222 },
223 'params': {'skip_download': 'm3u8'},
224 }, {
225 # multiple attachments/embeds
226 'url': 'https://www.patreon.com/posts/holy-wars-solos-100601977',
227 'playlist_count': 3,
228 'info_dict': {
229 'id': '100601977',
230 'title': '"Holy Wars" (Megadeth) Solos Transcription & Lesson/Analysis',
231 'description': 'md5:d099ab976edfce6de2a65c2b169a88d3',
232 'uploader': 'Bradley Hall',
233 'uploader_id': '24401883',
234 'uploader_url': 'https://www.patreon.com/bradleyhallguitar',
235 'channel_id': '3193932',
236 'channel_url': 'https://www.patreon.com/bradleyhallguitar',
237 'channel_follower_count': int,
238 'timestamp': 1710777855,
239 'upload_date': '20240318',
240 'like_count': int,
241 'comment_count': int,
242 'thumbnail': r're:^https?://.+',
243 },
244 'skip': 'Patron-only content',
245 }]
246 _RETURN_TYPE = 'video'
247
248 def _real_extract(self, url):
249 video_id = self._match_id(url)
250 post = self._call_api(
251 f'posts/{video_id}', video_id, query={
252 'fields[media]': 'download_url,mimetype,size_bytes',
253 'fields[post]': 'comment_count,content,embed,image,like_count,post_file,published_at,title,current_user_can_view',
254 'fields[user]': 'full_name,url',
255 'fields[post_tag]': 'value',
256 'fields[campaign]': 'url,name,patron_count',
257 'json-api-use-default-includes': 'false',
258 'include': 'audio,user,user_defined_tags,campaign,attachments_media',
259 })
260 attributes = post['data']['attributes']
261 info = traverse_obj(attributes, {
262 'title': ('title', {str.strip}),
263 'description': ('content', {clean_html}),
264 'thumbnail': ('image', ('large_url', 'url'), {url_or_none}, any),
265 'timestamp': ('published_at', {parse_iso8601}),
266 'like_count': ('like_count', {int_or_none}),
267 'comment_count': ('comment_count', {int_or_none}),
268 })
269
270 entries = []
271 idx = 0
272 for include in traverse_obj(post, ('included', lambda _, v: v['type'])):
273 include_type = include['type']
274 if include_type == 'media':
275 media_attributes = traverse_obj(include, ('attributes', {dict})) or {}
276 download_url = url_or_none(media_attributes.get('download_url'))
277 ext = mimetype2ext(media_attributes.get('mimetype'))
278
279 # if size_bytes is None, this media file is likely unavailable
280 # See: https://github.com/yt-dlp/yt-dlp/issues/4608
281 size_bytes = int_or_none(media_attributes.get('size_bytes'))
282 if download_url and ext in KNOWN_EXTENSIONS and size_bytes is not None:
283 idx += 1
284 entries.append({
285 'id': f'{video_id}-{idx}',
286 'ext': ext,
287 'filesize': size_bytes,
288 'url': download_url,
289 })
290
291 elif include_type == 'user':
292 info.update(traverse_obj(include, {
293 'uploader': ('attributes', 'full_name', {str}),
294 'uploader_id': ('id', {str_or_none}),
295 'uploader_url': ('attributes', 'url', {url_or_none}),
296 }))
297
298 elif include_type == 'post_tag':
299 if post_tag := traverse_obj(include, ('attributes', 'value', {str})):
300 info.setdefault('tags', []).append(post_tag)
301
302 elif include_type == 'campaign':
303 info.update(traverse_obj(include, {
304 'channel': ('attributes', 'title', {str}),
305 'channel_id': ('id', {str_or_none}),
306 'channel_url': ('attributes', 'url', {url_or_none}),
307 'channel_follower_count': ('attributes', 'patron_count', {int_or_none}),
308 }))
309
310 # all-lowercase 'referer' so we can smuggle it to Generic, SproutVideo, Vimeo
311 headers = {'referer': 'https://patreon.com/'}
312
313 # handle Vimeo embeds
314 if traverse_obj(attributes, ('embed', 'provider')) == 'Vimeo':
315 v_url = urllib.parse.unquote(self._html_search_regex(
316 r'(https(?:%3A%2F%2F|://)player\.vimeo\.com.+app_id(?:=|%3D)+\d+)',
317 traverse_obj(attributes, ('embed', 'html', {str})), 'vimeo url', fatal=False) or '')
318 if url_or_none(v_url) and self._request_webpage(
319 v_url, video_id, 'Checking Vimeo embed URL', headers=headers,
320 fatal=False, errnote=False, expected_status=429): # 429 is TLS fingerprint rejection
321 entries.append(self.url_result(
322 VimeoIE._smuggle_referrer(v_url, 'https://patreon.com/'),
323 VimeoIE, url_transparent=True))
324
325 embed_url = traverse_obj(attributes, ('embed', 'url', {url_or_none}))
326 if embed_url and (urlh := self._request_webpage(
327 embed_url, video_id, 'Checking embed URL', headers=headers,
328 fatal=False, errnote=False, expected_status=403)):
329 # Password-protected vids.io embeds return 403 errors w/o --video-password or session cookie
330 if urlh.status != 403 or VidsIoIE.suitable(embed_url):
331 entries.append(self.url_result(smuggle_url(embed_url, headers)))
332
333 post_file = traverse_obj(attributes, ('post_file', {dict}))
334 if post_file:
335 name = post_file.get('name')
336 ext = determine_ext(name)
337 if ext in KNOWN_EXTENSIONS:
338 entries.append({
339 'id': video_id,
340 'ext': ext,
341 'url': post_file['url'],
342 })
343 elif name == 'video' or determine_ext(post_file.get('url')) == 'm3u8':
344 formats, subtitles = self._extract_m3u8_formats_and_subtitles(post_file['url'], video_id)
345 entries.append({
346 'id': video_id,
347 'formats': formats,
348 'subtitles': subtitles,
349 })
350
351 can_view_post = traverse_obj(attributes, 'current_user_can_view')
352 comments = None
353 if can_view_post and info.get('comment_count'):
354 comments = self.extract_comments(video_id)
355
356 if not entries and can_view_post is False:
357 self.raise_no_formats('You do not have access to this post', video_id=video_id, expected=True)
358 elif not entries:
359 self.raise_no_formats('No supported media found in this post', video_id=video_id, expected=True)
360 elif len(entries) == 1:
361 info.update(entries[0])
362 else:
363 for entry in entries:
364 entry.update(info)
365 return self.playlist_result(entries, video_id, **info, __post_extractor=comments)
366
367 info['id'] = video_id
368 info['__post_extractor'] = comments
369 return info
370
371 def _get_comments(self, post_id):
372 cursor = None
373 count = 0
374 params = {
375 'page[count]': 50,
376 'include': 'parent.commenter.campaign,parent.post.user,parent.post.campaign.creator,parent.replies.parent,parent.replies.commenter.campaign,parent.replies.post.user,parent.replies.post.campaign.creator,commenter.campaign,post.user,post.campaign.creator,replies.parent,replies.commenter.campaign,replies.post.user,replies.post.campaign.creator,on_behalf_of_campaign',
377 'fields[comment]': 'body,created,is_by_creator',
378 'fields[user]': 'image_url,full_name,url',
379 'filter[flair]': 'image_tiny_url,name',
380 'sort': '-created',
381 'json-api-version': 1.0,
382 'json-api-use-default-includes': 'false',
383 }
384
385 for page in itertools.count(1):
386
387 params.update({'page[cursor]': cursor} if cursor else {})
388 response = self._call_api(
389 f'posts/{post_id}/comments', post_id, query=params, note=f'Downloading comments page {page}')
390
391 cursor = None
392 for comment in traverse_obj(response, (('data', ('included', lambda _, v: v['type'] == 'comment')), ...)):
393 count += 1
394 comment_id = comment.get('id')
395 attributes = comment.get('attributes') or {}
396 if comment_id is None:
397 continue
398 author_id = traverse_obj(comment, ('relationships', 'commenter', 'data', 'id'))
399 author_info = traverse_obj(
400 response, ('included', lambda _, v: v['id'] == author_id and v['type'] == 'user', 'attributes'),
401 get_all=False, expected_type=dict, default={})
402
403 yield {
404 'id': comment_id,
405 'text': attributes.get('body'),
406 'timestamp': parse_iso8601(attributes.get('created')),
407 'parent': traverse_obj(comment, ('relationships', 'parent', 'data', 'id'), default='root'),
408 'author_is_uploader': attributes.get('is_by_creator'),
409 'author_id': author_id,
410 'author': author_info.get('full_name'),
411 'author_thumbnail': author_info.get('image_url'),
412 }
413
414 if count < traverse_obj(response, ('meta', 'count')):
415 cursor = traverse_obj(response, ('data', -1, 'id'))
416
417 if cursor is None:
418 break
419
420
421 class PatreonCampaignIE(PatreonBaseIE):
422
423 _VALID_URL = r'https?://(?:www\.)?patreon\.com/(?!rss)(?:(?:m/(?P<campaign_id>\d+))|(?P<vanity>[-\w]+))'
424 _TESTS = [{
425 'url': 'https://www.patreon.com/dissonancepod/',
426 'info_dict': {
427 'title': 'Cognitive Dissonance Podcast',
428 'channel_url': 'https://www.patreon.com/dissonancepod',
429 'id': '80642',
430 'description': 'md5:eb2fa8b83da7ab887adeac34da6b7af7',
431 'channel_id': '80642',
432 'channel': 'Cognitive Dissonance Podcast',
433 'age_limit': 0,
434 'channel_follower_count': int,
435 'uploader_id': '87145',
436 'uploader_url': 'https://www.patreon.com/dissonancepod',
437 'uploader': 'Cognitive Dissonance Podcast',
438 'thumbnail': r're:^https?://.*$',
439 },
440 'playlist_mincount': 68,
441 }, {
442 'url': 'https://www.patreon.com/m/4767637/posts',
443 'info_dict': {
444 'title': 'Not Just Bikes',
445 'channel_follower_count': int,
446 'id': '4767637',
447 'channel_id': '4767637',
448 'channel_url': 'https://www.patreon.com/notjustbikes',
449 'description': 'md5:595c6e7dca76ae615b1d38c298a287a1',
450 'age_limit': 0,
451 'channel': 'Not Just Bikes',
452 'uploader_url': 'https://www.patreon.com/notjustbikes',
453 'uploader': 'Not Just Bikes',
454 'uploader_id': '37306634',
455 'thumbnail': r're:^https?://.*$',
456 },
457 'playlist_mincount': 71,
458 }, {
459 'url': 'https://www.patreon.com/dissonancepod/posts',
460 'only_matching': True,
461 }, {
462 'url': 'https://www.patreon.com/m/5932659',
463 'only_matching': True,
464 }]
465
466 @classmethod
467 def suitable(cls, url):
468 return False if PatreonIE.suitable(url) else super().suitable(url)
469
470 def _entries(self, campaign_id):
471 cursor = None
472 params = {
473 'fields[post]': 'patreon_url,url',
474 'filter[campaign_id]': campaign_id,
475 'filter[is_draft]': 'false',
476 'sort': '-published_at',
477 'json-api-use-default-includes': 'false',
478 }
479
480 for page in itertools.count(1):
481
482 params.update({'page[cursor]': cursor} if cursor else {})
483 posts_json = self._call_api('posts', campaign_id, query=params, note=f'Downloading posts page {page}')
484
485 cursor = traverse_obj(posts_json, ('meta', 'pagination', 'cursors', 'next'))
486 for post_url in traverse_obj(posts_json, ('data', ..., 'attributes', 'patreon_url')):
487 yield self.url_result(urljoin('https://www.patreon.com/', post_url), PatreonIE)
488
489 if cursor is None:
490 break
491
492 def _real_extract(self, url):
493
494 campaign_id, vanity = self._match_valid_url(url).group('campaign_id', 'vanity')
495 if campaign_id is None:
496 webpage = self._download_webpage(url, vanity, headers={'User-Agent': self.USER_AGENT})
497 campaign_id = self._search_nextjs_data(
498 webpage, vanity)['props']['pageProps']['bootstrapEnvelope']['pageBootstrap']['campaign']['data']['id']
499
500 params = {
501 'json-api-use-default-includes': 'false',
502 'fields[user]': 'full_name,url',
503 'fields[campaign]': 'name,summary,url,patron_count,creation_count,is_nsfw,avatar_photo_url',
504 'include': 'creator',
505 }
506
507 campaign_response = self._call_api(
508 f'campaigns/{campaign_id}', campaign_id,
509 note='Downloading campaign info', fatal=False,
510 query=params) or {}
511
512 campaign_info = campaign_response.get('data') or {}
513 channel_name = traverse_obj(campaign_info, ('attributes', 'name'))
514 user_info = traverse_obj(
515 campaign_response, ('included', lambda _, v: v['type'] == 'user'),
516 default={}, expected_type=dict, get_all=False)
517
518 return {
519 '_type': 'playlist',
520 'id': campaign_id,
521 'title': channel_name,
522 'entries': self._entries(campaign_id),
523 'description': clean_html(traverse_obj(campaign_info, ('attributes', 'summary'))),
524 'channel_url': traverse_obj(campaign_info, ('attributes', 'url')),
525 'channel_follower_count': int_or_none(traverse_obj(campaign_info, ('attributes', 'patron_count'))),
526 'channel_id': campaign_id,
527 'channel': channel_name,
528 'uploader_url': traverse_obj(user_info, ('attributes', 'url')),
529 'uploader_id': str_or_none(user_info.get('id')),
530 'uploader': traverse_obj(user_info, ('attributes', 'full_name')),
531 'playlist_count': traverse_obj(campaign_info, ('attributes', 'creation_count')),
532 'age_limit': 18 if traverse_obj(campaign_info, ('attributes', 'is_nsfw')) else 0,
533 'thumbnail': url_or_none(traverse_obj(campaign_info, ('attributes', 'avatar_photo_url'))),
534 }