[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / patreon.py
blob4489d533a600fc8fb3676e01477fbeaebadfacd2
1 import itertools
2 import urllib.parse
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,
24 class PatreonBaseIE(InfoExtractor):
25 USER_AGENT = 'Patreon/7.6.28 (Android; Android 11; Scale/2.10)'
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})
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
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,
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',
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',
115 'params': {
116 'noplaylist': True,
117 'skip_download': True,
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',
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,
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',
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',
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?://.+',
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?://.+',
244 'skip': 'Patron-only content',
246 _RETURN_TYPE = 'video'
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',
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}),
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'))
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,
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}),
298 elif include_type == 'post_tag':
299 if post_tag := traverse_obj(include, ('attributes', 'value', {str})):
300 info.setdefault('tags', []).append(post_tag)
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}),
310 # all-lowercase 'referer' so we can smuggle it to Generic, SproutVideo, Vimeo
311 headers = {'referer': 'https://patreon.com/'}
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))
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)))
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'],
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,
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)
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)
367 info['id'] = video_id
368 info['__post_extractor'] = comments
369 return info
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',
385 for page in itertools.count(1):
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}')
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={})
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'),
414 if count < traverse_obj(response, ('meta', 'count')):
415 cursor = traverse_obj(response, ('data', -1, 'id'))
417 if cursor is None:
418 break
421 class PatreonCampaignIE(PatreonBaseIE):
423 _VALID_URL = r'https?://(?:www\.)?patreon\.com/(?!rss)(?:(?:m|api/campaigns)/(?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?://.*$',
440 'playlist_mincount': 68,
441 }, {
442 'url': 'https://www.patreon.com/m/4767637/posts',
443 'info_dict': {
444 'title': 'Not Just Bikes',
445 'id': '4767637',
446 'channel_id': '4767637',
447 'channel_url': 'https://www.patreon.com/notjustbikes',
448 'description': 'md5:9f4b70051216c4d5c58afe580ffc8d0f',
449 'age_limit': 0,
450 'channel': 'Not Just Bikes',
451 'uploader_url': 'https://www.patreon.com/notjustbikes',
452 'uploader': 'Jason',
453 'uploader_id': '37306634',
454 'thumbnail': r're:^https?://.*$',
456 'playlist_mincount': 71,
457 }, {
458 'url': 'https://www.patreon.com/api/campaigns/4243769/posts',
459 'info_dict': {
460 'title': 'Second Thought',
461 'channel_follower_count': int,
462 'id': '4243769',
463 'channel_id': '4243769',
464 'channel_url': 'https://www.patreon.com/secondthought',
465 'description': 'md5:69c89a3aba43efdb76e85eb023e8de8b',
466 'age_limit': 0,
467 'channel': 'Second Thought',
468 'uploader_url': 'https://www.patreon.com/secondthought',
469 'uploader': 'JT Chapman',
470 'uploader_id': '32718287',
471 'thumbnail': r're:^https?://.*$',
473 'playlist_mincount': 201,
474 }, {
475 'url': 'https://www.patreon.com/dissonancepod/posts',
476 'only_matching': True,
477 }, {
478 'url': 'https://www.patreon.com/m/5932659',
479 'only_matching': True,
480 }, {
481 'url': 'https://www.patreon.com/api/campaigns/4243769',
482 'only_matching': True,
485 @classmethod
486 def suitable(cls, url):
487 return False if PatreonIE.suitable(url) else super().suitable(url)
489 def _entries(self, campaign_id):
490 cursor = None
491 params = {
492 'fields[post]': 'patreon_url,url',
493 'filter[campaign_id]': campaign_id,
494 'filter[is_draft]': 'false',
495 'sort': '-published_at',
496 'json-api-use-default-includes': 'false',
499 for page in itertools.count(1):
501 params.update({'page[cursor]': cursor} if cursor else {})
502 posts_json = self._call_api('posts', campaign_id, query=params, note=f'Downloading posts page {page}')
504 cursor = traverse_obj(posts_json, ('meta', 'pagination', 'cursors', 'next'))
505 for post_url in traverse_obj(posts_json, ('data', ..., 'attributes', 'patreon_url')):
506 yield self.url_result(urljoin('https://www.patreon.com/', post_url), PatreonIE)
508 if cursor is None:
509 break
511 def _real_extract(self, url):
513 campaign_id, vanity = self._match_valid_url(url).group('campaign_id', 'vanity')
514 if campaign_id is None:
515 webpage = self._download_webpage(url, vanity, headers={'User-Agent': self.USER_AGENT})
516 campaign_id = self._search_nextjs_data(
517 webpage, vanity)['props']['pageProps']['bootstrapEnvelope']['pageBootstrap']['campaign']['data']['id']
519 params = {
520 'json-api-use-default-includes': 'false',
521 'fields[user]': 'full_name,url',
522 'fields[campaign]': 'name,summary,url,patron_count,creation_count,is_nsfw,avatar_photo_url',
523 'include': 'creator',
526 campaign_response = self._call_api(
527 f'campaigns/{campaign_id}', campaign_id,
528 note='Downloading campaign info', fatal=False,
529 query=params) or {}
531 campaign_info = campaign_response.get('data') or {}
532 channel_name = traverse_obj(campaign_info, ('attributes', 'name'))
533 user_info = traverse_obj(
534 campaign_response, ('included', lambda _, v: v['type'] == 'user'),
535 default={}, expected_type=dict, get_all=False)
537 return {
538 '_type': 'playlist',
539 'id': campaign_id,
540 'title': channel_name,
541 'entries': self._entries(campaign_id),
542 'description': clean_html(traverse_obj(campaign_info, ('attributes', 'summary'))),
543 'channel_url': traverse_obj(campaign_info, ('attributes', 'url')),
544 'channel_follower_count': int_or_none(traverse_obj(campaign_info, ('attributes', 'patron_count'))),
545 'channel_id': campaign_id,
546 'channel': channel_name,
547 'uploader_url': traverse_obj(user_info, ('attributes', 'url')),
548 'uploader_id': str_or_none(user_info.get('id')),
549 'uploader': traverse_obj(user_info, ('attributes', 'full_name')),
550 'playlist_count': traverse_obj(campaign_info, ('attributes', 'creation_count')),
551 'age_limit': 18 if traverse_obj(campaign_info, ('attributes', 'is_nsfw')) else 0,
552 'thumbnail': url_or_none(traverse_obj(campaign_info, ('attributes', 'avatar_photo_url'))),