]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/patreon.py
[patreon] Fix vimeo player regex (#1332)
[yt-dlp.git] / yt_dlp / extractor / patreon.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5
6 from .common import InfoExtractor
7 from .vimeo import VimeoIE
8
9 from ..compat import compat_urllib_parse_unquote
10 from ..utils import (
11 clean_html,
12 determine_ext,
13 int_or_none,
14 KNOWN_EXTENSIONS,
15 mimetype2ext,
16 parse_iso8601,
17 str_or_none,
18 try_get,
19 url_or_none,
20 )
21
22
23 class PatreonIE(InfoExtractor):
24 _VALID_URL = r'https?://(?:www\.)?patreon\.com/(?:creation\?hid=|posts/(?:[\w-]+-)?)(?P<id>\d+)'
25 _TESTS = [{
26 'url': 'http://www.patreon.com/creation?hid=743933',
27 'md5': 'e25505eec1053a6e6813b8ed369875cc',
28 'info_dict': {
29 'id': '743933',
30 'ext': 'mp3',
31 'title': 'Episode 166: David Smalley of Dogma Debate',
32 'description': 'md5:713b08b772cd6271b9f3906683cfacdf',
33 'uploader': 'Cognitive Dissonance Podcast',
34 'thumbnail': 're:^https?://.*$',
35 'timestamp': 1406473987,
36 'upload_date': '20140727',
37 'uploader_id': '87145',
38 },
39 }, {
40 'url': 'http://www.patreon.com/creation?hid=754133',
41 'md5': '3eb09345bf44bf60451b8b0b81759d0a',
42 'info_dict': {
43 'id': '754133',
44 'ext': 'mp3',
45 'title': 'CD 167 Extra',
46 'uploader': 'Cognitive Dissonance Podcast',
47 'thumbnail': 're:^https?://.*$',
48 },
49 'skip': 'Patron-only content',
50 }, {
51 'url': 'https://www.patreon.com/creation?hid=1682498',
52 'info_dict': {
53 'id': 'SU4fj_aEMVw',
54 'ext': 'mp4',
55 'title': 'I\'m on Patreon!',
56 'uploader': 'TraciJHines',
57 'thumbnail': 're:^https?://.*$',
58 'upload_date': '20150211',
59 'description': 'md5:c5a706b1f687817a3de09db1eb93acd4',
60 'uploader_id': 'TraciJHines',
61 },
62 'params': {
63 'noplaylist': True,
64 'skip_download': True,
65 }
66 }, {
67 'url': 'https://www.patreon.com/posts/episode-166-of-743933',
68 'only_matching': True,
69 }, {
70 'url': 'https://www.patreon.com/posts/743933',
71 'only_matching': True,
72 }, {
73 'url': 'https://www.patreon.com/posts/kitchen-as-seen-51706779',
74 'md5': '96656690071f6d64895866008484251b',
75 'info_dict': {
76 'id': '555089736',
77 'ext': 'mp4',
78 'title': 'KITCHEN AS SEEN ON DEEZ NUTS EXTENDED!',
79 'uploader': 'Cold Ones',
80 'thumbnail': 're:^https?://.*$',
81 'upload_date': '20210526',
82 'description': 'md5:557a409bd79d3898689419094934ba79',
83 'uploader_id': '14936315',
84 },
85 'skip': 'Patron-only content'
86 }]
87
88 # Currently Patreon exposes download URL via hidden CSS, so login is not
89 # needed. Keeping this commented for when this inevitably changes.
90 '''
91 def _login(self):
92 username, password = self._get_login_info()
93 if username is None:
94 return
95
96 login_form = {
97 'redirectUrl': 'http://www.patreon.com/',
98 'email': username,
99 'password': password,
100 }
101
102 request = sanitized_Request(
103 'https://www.patreon.com/processLogin',
104 compat_urllib_parse_urlencode(login_form).encode('utf-8')
105 )
106 login_page = self._download_webpage(request, None, note='Logging in')
107
108 if re.search(r'onLoginFailed', login_page):
109 raise ExtractorError('Unable to login, incorrect username and/or password', expected=True)
110
111 def _real_initialize(self):
112 self._login()
113 '''
114
115 def _real_extract(self, url):
116 video_id = self._match_id(url)
117 post = self._download_json(
118 'https://www.patreon.com/api/posts/' + video_id, video_id, query={
119 'fields[media]': 'download_url,mimetype,size_bytes',
120 'fields[post]': 'comment_count,content,embed,image,like_count,post_file,published_at,title',
121 'fields[user]': 'full_name,url',
122 'json-api-use-default-includes': 'false',
123 'include': 'media,user',
124 })
125 attributes = post['data']['attributes']
126 title = attributes['title'].strip()
127 image = attributes.get('image') or {}
128 info = {
129 'id': video_id,
130 'title': title,
131 'description': clean_html(attributes.get('content')),
132 'thumbnail': image.get('large_url') or image.get('url'),
133 'timestamp': parse_iso8601(attributes.get('published_at')),
134 'like_count': int_or_none(attributes.get('like_count')),
135 'comment_count': int_or_none(attributes.get('comment_count')),
136 }
137
138 for i in post.get('included', []):
139 i_type = i.get('type')
140 if i_type == 'media':
141 media_attributes = i.get('attributes') or {}
142 download_url = media_attributes.get('download_url')
143 ext = mimetype2ext(media_attributes.get('mimetype'))
144 if download_url and ext in KNOWN_EXTENSIONS:
145 info.update({
146 'ext': ext,
147 'filesize': int_or_none(media_attributes.get('size_bytes')),
148 'url': download_url,
149 })
150 elif i_type == 'user':
151 user_attributes = i.get('attributes')
152 if user_attributes:
153 info.update({
154 'uploader': user_attributes.get('full_name'),
155 'uploader_id': str_or_none(i.get('id')),
156 'uploader_url': user_attributes.get('url'),
157 })
158
159 if not info.get('url'):
160 # handle Vimeo embeds
161 if try_get(attributes, lambda x: x['embed']['provider']) == 'Vimeo':
162 embed_html = try_get(attributes, lambda x: x['embed']['html'])
163 v_url = url_or_none(compat_urllib_parse_unquote(
164 self._search_regex(r'(https(?:%3A%2F%2F|://)player\.vimeo\.com.+app_id(?:=|%3D)+\d+)', embed_html, 'vimeo url', fatal=False)))
165 if v_url:
166 info.update({
167 '_type': 'url_transparent',
168 'url': VimeoIE._smuggle_referrer(v_url, 'https://patreon.com'),
169 'ie_key': 'Vimeo',
170 })
171
172 if not info.get('url'):
173 embed_url = try_get(attributes, lambda x: x['embed']['url'])
174 if embed_url:
175 info.update({
176 '_type': 'url',
177 'url': embed_url,
178 })
179
180 if not info.get('url'):
181 post_file = attributes['post_file']
182 ext = determine_ext(post_file.get('name'))
183 if ext in KNOWN_EXTENSIONS:
184 info.update({
185 'ext': ext,
186 'url': post_file['url'],
187 })
188
189 return info
190
191
192 class PatreonUserIE(InfoExtractor):
193
194 _VALID_URL = r'https?://(?:www\.)?patreon\.com/(?P<id>[-_\w\d]+)/?(?:posts/?)?'
195
196 _TESTS = [{
197 'url': 'https://www.patreon.com/dissonancepod/',
198 'info_dict': {
199 'title': 'dissonancepod',
200 },
201 'playlist_mincount': 68,
202 'expected_warnings': 'Post not viewable by current user! Skipping!',
203 }, {
204 'url': 'https://www.patreon.com/dissonancepod/posts',
205 'only_matching': True
206 }, ]
207
208 @classmethod
209 def suitable(cls, url):
210 return False if PatreonIE.suitable(url) else super(PatreonUserIE, cls).suitable(url)
211
212 def _entries(self, campaign_id, user_id):
213 cursor = None
214 params = {
215 'fields[campaign]': 'show_audio_post_download_links,name,url',
216 'fields[post]': 'current_user_can_view,embed,image,is_paid,post_file,published_at,patreon_url,url,post_type,thumbnail_url,title',
217 'filter[campaign_id]': campaign_id,
218 'filter[is_draft]': 'false',
219 'sort': '-published_at',
220 'json-api-version': 1.0,
221 'json-api-use-default-includes': 'false',
222 }
223
224 for page in itertools.count(1):
225
226 params.update({'page[cursor]': cursor} if cursor else {})
227 posts_json = self._download_json('https://www.patreon.com/api/posts', user_id, note='Downloading posts page %d' % page, query=params, headers={'Cookie': '.'})
228
229 cursor = try_get(posts_json, lambda x: x['meta']['pagination']['cursors']['next'])
230
231 for post in posts_json.get('data') or []:
232 yield self.url_result(url_or_none(try_get(post, lambda x: x['attributes']['patreon_url'])), 'Patreon')
233
234 if cursor is None:
235 break
236
237 def _real_extract(self, url):
238
239 user_id = self._match_id(url)
240 webpage = self._download_webpage(url, user_id, headers={'Cookie': '.'})
241 campaign_id = self._search_regex(r'https://www.patreon.com/api/campaigns/(\d+)/?', webpage, 'Campaign ID')
242 return self.playlist_result(self._entries(campaign_id, user_id), playlist_title=user_id)