]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/pornhub.py
[cleanup] Upgrade syntax
[yt-dlp.git] / yt_dlp / extractor / pornhub.py
CommitLineData
21fbf0f9 1import functools
34541395 2import itertools
df2a5633 3import math
21fbf0f9 4import operator
125cfd78 5import re
6
7from .common import InfoExtractor
1cc79574 8from ..compat import (
34541395 9 compat_HTTPError,
79367a98 10 compat_str,
278d061a 11 compat_urllib_request,
1cc79574 12)
278d061a 13from .openload import PhantomJSwrapper
1cc79574 14from ..utils import (
d0fb4bd1 15 clean_html,
b8526c78 16 determine_ext,
50789175 17 ExtractorError,
e0ddbd02 18 format_field,
ed8648a3 19 int_or_none,
cd85a1bb 20 merge_dicts,
0164cd5d 21 NO_DEFAULT,
8f9a477e 22 orderedSet,
e1e35d1a 23 remove_quotes,
0320ddc1 24 str_to_int,
2181983a 25 update_url_query,
26 urlencode_postdata,
4938c8d5 27 url_or_none,
125cfd78 28)
125cfd78 29
9933b574 30
71a1f617 31class PornHubBaseIE(InfoExtractor):
2181983a 32 _NETRC_MACHINE = 'pornhub'
4c968755 33 _PORNHUB_HOST_RE = r'(?:(?P<host>pornhub(?:premium)?\.(?:com|net|org))|pornhubvybmsymdol4iibwgwtkpwmeyd6luq2gxajgjzfjvotyt5zhyd\.onion)'
2181983a 34
71a1f617
S
35 def _download_webpage_handle(self, *args, **kwargs):
36 def dl(*args, **kwargs):
37 return super(PornHubBaseIE, self)._download_webpage_handle(*args, **kwargs)
38
29f7c58a 39 ret = dl(*args, **kwargs)
40
41 if not ret:
42 return ret
43
44 webpage, urlh = ret
71a1f617
S
45
46 if any(re.search(p, webpage) for p in (
47 r'<body\b[^>]+\bonload=["\']go\(\)',
48 r'document\.cookie\s*=\s*["\']RNKEY=',
49 r'document\.location\.reload\(true\)')):
50 url_or_request = args[0]
51 url = (url_or_request.get_full_url()
52 if isinstance(url_or_request, compat_urllib_request.Request)
53 else url_or_request)
54 phantom = PhantomJSwrapper(self, required_version='2.0')
55 phantom.get(url, html=webpage)
56 webpage, urlh = dl(*args, **kwargs)
57
58 return webpage, urlh
59
2181983a 60 def _real_initialize(self):
61 self._logged_in = False
62
63 def _login(self, host):
64 if self._logged_in:
65 return
66
67 site = host.split('.')[0]
68
69 # Both sites pornhub and pornhubpremium have separate accounts
70 # so there should be an option to provide credentials for both.
71 # At the same time some videos are available under the same video id
72 # on both sites so that we have to identify them as the same video.
73 # For that purpose we have to keep both in the same extractor
74 # but under different netrc machines.
75 username, password = self._get_login_info(netrc_machine=site)
76 if username is None:
77 return
78
79 login_url = 'https://www.%s/%slogin' % (host, 'premium/' if 'premium' in host else '')
80 login_page = self._download_webpage(
81 login_url, None, 'Downloading %s login page' % site)
82
83 def is_logged(webpage):
84 return any(re.search(p, webpage) for p in (
85 r'class=["\']signOut',
86 r'>Sign\s+[Oo]ut\s*<'))
87
88 if is_logged(login_page):
89 self._logged_in = True
90 return
91
92 login_form = self._hidden_inputs(login_page)
93
94 login_form.update({
95 'username': username,
96 'password': password,
97 })
98
99 response = self._download_json(
100 'https://www.%s/front/authenticate' % host, None,
101 'Logging in to %s' % site,
102 data=urlencode_postdata(login_form),
103 headers={
104 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
105 'Referer': login_url,
106 'X-Requested-With': 'XMLHttpRequest',
107 })
108
109 if response.get('success') == '1':
110 self._logged_in = True
111 return
112
113 message = response.get('message')
114 if message is not None:
115 raise ExtractorError(
116 'Unable to login: %s' % message, expected=True)
117
118 raise ExtractorError('Unable to log in')
119
71a1f617
S
120
121class PornHubIE(PornHubBaseIE):
bc4b2d75
S
122 IE_DESC = 'PornHub and Thumbzilla'
123 _VALID_URL = r'''(?x)
124 https?://
125 (?:
ed807c18 126 (?:[^/]+\.)?
127 %s
128 /(?:(?:view_video\.php|video/show)\?viewkey=|embed/)|
bc4b2d75
S
129 (?:www\.)?thumbzilla\.com/video/
130 )
b52c9ef1 131 (?P<id>[\da-z]+)
ed807c18 132 ''' % PornHubBaseIE._PORNHUB_HOST_RE
360075e2 133 _TESTS = [{
9933b574 134 'url': 'http://www.pornhub.com/view_video.php?viewkey=648719015',
cd85a1bb 135 'md5': 'a6391306d050e4547f62b3f485dd9ba9',
9933b574 136 'info_dict': {
249efaf4
PH
137 'id': '648719015',
138 'ext': 'mp4',
611c1dd9 139 'title': 'Seductive Indian beauty strips down and fingers her pink pussy',
ed8648a3 140 'uploader': 'Babes',
3661ebf2 141 'upload_date': '20130628',
cd85a1bb 142 'timestamp': 1372447216,
ed8648a3
S
143 'duration': 361,
144 'view_count': int,
145 'like_count': int,
146 'dislike_count': int,
147 'comment_count': int,
148 'age_limit': 18,
6bb05b32
YCH
149 'tags': list,
150 'categories': list,
d0fb4bd1 151 'cast': list,
6c376029
S
152 },
153 }, {
154 # non-ASCII title
155 'url': 'http://www.pornhub.com/view_video.php?viewkey=1331683002',
156 'info_dict': {
157 'id': '1331683002',
158 'ext': 'mp4',
159 'title': '重庆婷婷女王足交',
3661ebf2 160 'upload_date': '20150213',
cd85a1bb 161 'timestamp': 1423804862,
6c376029
S
162 'duration': 1753,
163 'view_count': int,
164 'like_count': int,
165 'dislike_count': int,
166 'comment_count': int,
167 'age_limit': 18,
6bb05b32
YCH
168 'tags': list,
169 'categories': list,
6c376029
S
170 },
171 'params': {
172 'skip_download': True,
173 },
10db0d2f 174 'skip': 'Video has been flagged for verification in accordance with our trust and safety policy',
4938c8d5
GF
175 }, {
176 # subtitles
177 'url': 'https://www.pornhub.com/view_video.php?viewkey=ph5af5fef7c2aa7',
178 'info_dict': {
179 'id': 'ph5af5fef7c2aa7',
180 'ext': 'mp4',
181 'title': 'BFFS - Cute Teen Girls Share Cock On the Floor',
182 'uploader': 'BFFs',
183 'duration': 622,
184 'view_count': int,
185 'like_count': int,
186 'dislike_count': int,
187 'comment_count': int,
188 'age_limit': 18,
189 'tags': list,
190 'categories': list,
191 'subtitles': {
192 'en': [{
193 "ext": 'srt'
194 }]
195 },
196 },
197 'params': {
198 'skip_download': True,
199 },
cd85a1bb 200 'skip': 'This video has been disabled',
360075e2
S
201 }, {
202 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph557bbb6676d2d',
203 'only_matching': True,
272e4db5 204 }, {
eaaaaec0 205 # removed at the request of cam4.com
272e4db5
S
206 'url': 'http://fr.pornhub.com/view_video.php?viewkey=ph55ca2f9760862',
207 'only_matching': True,
eaaaaec0
S
208 }, {
209 # removed at the request of the copyright owner
210 'url': 'http://www.pornhub.com/view_video.php?viewkey=788152859',
211 'only_matching': True,
212 }, {
213 # removed by uploader
214 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph572716d15a111',
215 'only_matching': True,
195f0845
S
216 }, {
217 # private video
218 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph56fd731fce6b7',
219 'only_matching': True,
bc4b2d75
S
220 }, {
221 'url': 'https://www.thumbzilla.com/video/ph56c6114abd99a/horny-girlfriend-sex',
222 'only_matching': True,
a99cc4ca
S
223 }, {
224 'url': 'http://www.pornhub.com/video/show?viewkey=648719015',
225 'only_matching': True,
f97c0991
S
226 }, {
227 'url': 'https://www.pornhub.net/view_video.php?viewkey=203640933',
228 'only_matching': True,
29f7c58a 229 }, {
230 'url': 'https://www.pornhub.org/view_video.php?viewkey=203640933',
231 'only_matching': True,
fa9b8c66
TW
232 }, {
233 'url': 'https://www.pornhubpremium.com/view_video.php?viewkey=ph5e4acdae54a82',
234 'only_matching': True,
2181983a 235 }, {
236 # Some videos are available with the same id on both premium
237 # and non-premium sites (e.g. this and the following test)
238 'url': 'https://www.pornhub.com/view_video.php?viewkey=ph5f75b0f4b18e3',
239 'only_matching': True,
240 }, {
241 'url': 'https://www.pornhubpremium.com/view_video.php?viewkey=ph5f75b0f4b18e3',
242 'only_matching': True,
ed807c18 243 }, {
244 # geo restricted
245 'url': 'https://www.pornhub.com/view_video.php?viewkey=ph5a9813bfa7156',
246 'only_matching': True,
247 }, {
4c968755 248 'url': 'http://pornhubvybmsymdol4iibwgwtkpwmeyd6luq2gxajgjzfjvotyt5zhyd.onion/view_video.php?viewkey=ph5a9813bfa7156',
ed807c18 249 'only_matching': True,
360075e2 250 }]
125cfd78 251
b52c9ef1
S
252 @staticmethod
253 def _extract_urls(webpage):
254 return re.findall(
2181983a 255 r'<iframe[^>]+?src=["\'](?P<url>(?:https?:)?//(?:www\.)?pornhub(?:premium)?\.(?:com|net|org)/embed/[\da-z]+)',
b52c9ef1 256 webpage)
65d161c4 257
0320ddc1 258 def _extract_count(self, pattern, webpage, name):
b69fd25c 259 return str_to_int(self._search_regex(pattern, webpage, '%s count' % name, default=None))
0320ddc1 260
125cfd78 261 def _real_extract(self, url):
5ad28e7f 262 mobj = self._match_valid_url(url)
3430ff9b
S
263 host = mobj.group('host') or 'pornhub.com'
264 video_id = mobj.group('id')
7399ca1f 265
2181983a 266 self._login(host)
fa9b8c66 267
3430ff9b 268 self._set_cookie(host, 'age_verified', '1')
125cfd78 269
9a372f14 270 def dl_webpage(platform):
3430ff9b 271 self._set_cookie(host, 'platform', platform)
9a372f14 272 return self._download_webpage(
2c53c0eb 273 'https://www.%s/view_video.php?viewkey=%s' % (host, video_id),
79367a98 274 video_id, 'Downloading %s webpage' % platform)
9a372f14
S
275
276 webpage = dl_webpage('pc')
125cfd78 277
50789175 278 error_msg = self._html_search_regex(
10db0d2f 279 (r'(?s)<div[^>]+class=(["\'])(?:(?!\1).)*\b(?:removed|userMessageSection)\b(?:(?!\1).)*\1[^>]*>(?P<error>.+?)</div>',
280 r'(?s)<section[^>]+class=["\']noVideo["\'][^>]*>(?P<error>.+?)</section>'),
3cb3b600 281 webpage, 'error message', default=None, group='error')
50789175
PH
282 if error_msg:
283 error_msg = re.sub(r'\s+', ' ', error_msg)
284 raise ExtractorError(
285 'PornHub said: %s' % error_msg,
286 expected=True, video_id=video_id)
287
ed807c18 288 if any(re.search(p, webpage) for p in (
289 r'class=["\']geoBlocked["\']',
290 r'>\s*This content is unavailable in your country')):
291 self.raise_geo_restricted()
292
6c376029
S
293 # video_title from flashvars contains whitespace instead of non-ASCII (see
294 # http://www.pornhub.com/view_video.php?viewkey=1331683002), not relying
295 # on that anymore.
79367a98 296 title = self._html_search_meta(
46cc54ca
S
297 'twitter:title', webpage, default=None) or self._html_search_regex(
298 (r'(?s)<h1[^>]+class=["\']title["\'][^>]*>(?P<title>.+?)</h1>',
299 r'<div[^>]+data-video-title=(["\'])(?P<title>(?:(?!\1).)+)\1',
300 r'shareTitle["\']\s*[=:]\s*(["\'])(?P<title>(?:(?!\1).)+)\1'),
6c376029
S
301 webpage, 'title', group='title')
302
79367a98
S
303 video_urls = []
304 video_urls_set = set()
4938c8d5 305 subtitles = {}
79367a98 306
ed8648a3
S
307 flashvars = self._parse_json(
308 self._search_regex(
03442072 309 r'var\s+flashvars_\d+\s*=\s*({.+?});', webpage, 'flashvars', default='{}'),
ed8648a3
S
310 video_id)
311 if flashvars:
4938c8d5
GF
312 subtitle_url = url_or_none(flashvars.get('closedCaptionsFile'))
313 if subtitle_url:
314 subtitles.setdefault('en', []).append({
315 'url': subtitle_url,
316 'ext': 'srt',
317 })
ed8648a3
S
318 thumbnail = flashvars.get('image_url')
319 duration = int_or_none(flashvars.get('video_duration'))
79367a98
S
320 media_definitions = flashvars.get('mediaDefinitions')
321 if isinstance(media_definitions, list):
322 for definition in media_definitions:
323 if not isinstance(definition, dict):
324 continue
325 video_url = definition.get('videoUrl')
326 if not video_url or not isinstance(video_url, compat_str):
327 continue
328 if video_url in video_urls_set:
329 continue
330 video_urls_set.add(video_url)
331 video_urls.append(
332 (video_url, int_or_none(definition.get('quality'))))
ed8648a3 333 else:
79367a98
S
334 thumbnail, duration = [None] * 2
335
0164cd5d 336 def extract_js_vars(webpage, pattern, default=NO_DEFAULT):
79367a98 337 assignments = self._search_regex(
0164cd5d 338 pattern, webpage, 'encoded url', default=default)
f4134726
S
339 if not assignments:
340 return {}
341
342 assignments = assignments.split(';')
79367a98
S
343
344 js_vars = {}
345
346 def parse_js_value(inp):
347 inp = re.sub(r'/\*(?:(?!\*/).)*?\*/', '', inp)
348 if '+' in inp:
349 inps = inp.split('+')
350 return functools.reduce(
351 operator.concat, map(parse_js_value, inps))
352 inp = inp.strip()
353 if inp in js_vars:
354 return js_vars[inp]
355 return remove_quotes(inp)
356
357 for assn in assignments:
358 assn = assn.strip()
359 if not assn:
360 continue
361 assn = re.sub(r'var\s+', '', assn)
362 vname, value = assn.split('=', 1)
363 js_vars[vname] = parse_js_value(value)
f4134726 364 return js_vars
79367a98 365
f4134726
S
366 def add_video_url(video_url):
367 v_url = url_or_none(video_url)
368 if not v_url:
369 return
370 if v_url in video_urls_set:
371 return
372 video_urls.append((v_url, None))
373 video_urls_set.add(v_url)
374
29f7c58a 375 def parse_quality_items(quality_items):
376 q_items = self._parse_json(quality_items, video_id, fatal=False)
377 if not isinstance(q_items, list):
378 return
379 for item in q_items:
380 if isinstance(item, dict):
381 add_video_url(item.get('url'))
382
f4134726 383 if not video_urls:
29f7c58a 384 FORMAT_PREFIXES = ('media', 'quality', 'qualityItems')
f4134726
S
385 js_vars = extract_js_vars(
386 webpage, r'(var\s+(?:%s)_.+)' % '|'.join(FORMAT_PREFIXES),
0164cd5d 387 default=None)
f4134726
S
388 if js_vars:
389 for key, format_url in js_vars.items():
29f7c58a 390 if key.startswith(FORMAT_PREFIXES[-1]):
391 parse_quality_items(format_url)
392 elif any(key.startswith(p) for p in FORMAT_PREFIXES[:2]):
f4134726 393 add_video_url(format_url)
0164cd5d
S
394 if not video_urls and re.search(
395 r'<[^>]+\bid=["\']lockedPlayer', webpage):
396 raise ExtractorError(
397 'Video %s is locked' % video_id, expected=True)
f4134726
S
398
399 if not video_urls:
400 js_vars = extract_js_vars(
401 dl_webpage('tv'), r'(var.+?mediastring.+?)</script>')
402 add_video_url(js_vars['mediastring'])
79367a98
S
403
404 for mobj in re.finditer(
405 r'<a[^>]+\bclass=["\']downloadBtn\b[^>]+\bhref=(["\'])(?P<url>(?:(?!\1).)+)\1',
406 webpage):
407 video_url = mobj.group('url')
408 if video_url not in video_urls_set:
409 video_urls.append((video_url, None))
410 video_urls_set.add(video_url)
411
3661ebf2 412 upload_date = None
79367a98 413 formats = []
10db0d2f 414
415 def add_format(format_url, height=None):
f7ad7160 416 ext = determine_ext(format_url)
417 if ext == 'mpd':
418 formats.extend(self._extract_mpd_formats(
419 format_url, video_id, mpd_id='dash', fatal=False))
420 return
421 if ext == 'm3u8':
422 formats.extend(self._extract_m3u8_formats(
423 format_url, video_id, 'mp4', entry_protocol='m3u8_native',
424 m3u8_id='hls', fatal=False))
425 return
ed807c18 426 if not height:
427 height = int_or_none(self._search_regex(
428 r'(?P<height>\d+)[pP]?_\d+[kK]', format_url, 'height',
429 default=None))
10db0d2f 430 formats.append({
431 'url': format_url,
e0ddbd02 432 'format_id': format_field(height, template='%dp'),
10db0d2f 433 'height': height,
10db0d2f 434 })
435
79367a98 436 for video_url, height in video_urls:
3661ebf2
S
437 if not upload_date:
438 upload_date = self._search_regex(
439 r'/(\d{6}/\d{2})/', video_url, 'upload data', default=None)
440 if upload_date:
441 upload_date = upload_date.replace('/', '')
10db0d2f 442 if '/video/get_media' in video_url:
443 medias = self._download_json(video_url, video_id, fatal=False)
444 if isinstance(medias, list):
445 for media in medias:
446 if not isinstance(media, dict):
447 continue
448 video_url = url_or_none(media.get('videoUrl'))
449 if not video_url:
450 continue
451 height = int_or_none(media.get('quality'))
452 add_format(video_url, height)
453 continue
454 add_format(video_url)
ed807c18 455
456 # field_preference is unnecessary here, but kept for code-similarity with youtube-dl
457 self._sort_formats(
458 formats, field_preference=('height', 'width', 'fps', 'format_id'))
ed8648a3 459
0320ddc1 460 video_uploader = self._html_search_regex(
2d4fe594 461 r'(?s)From:&nbsp;.+?<(?:a\b[^>]+\bhref=["\']/(?:(?:user|channel)s|model|pornstar)/|span\b[^>]+\bclass=["\']username)[^>]+>(.+?)<',
cd85a1bb 462 webpage, 'uploader', default=None)
125cfd78 463
29f7c58a 464 def extract_vote_count(kind, name):
465 return self._extract_count(
466 (r'<span[^>]+\bclass="votes%s"[^>]*>([\d,\.]+)</span>' % kind,
467 r'<span[^>]+\bclass=["\']votes%s["\'][^>]*\bdata-rating=["\'](\d+)' % kind),
468 webpage, name)
469
7700207e 470 view_count = self._extract_count(
540b9f51 471 r'<span class="count">([\d,\.]+)</span> [Vv]iews', webpage, 'view')
29f7c58a 472 like_count = extract_vote_count('Up', 'like')
473 dislike_count = extract_vote_count('Down', 'dislike')
0320ddc1 474 comment_count = self._extract_count(
7700207e 475 r'All Comments\s*<span>\(([\d,.]+)\)', webpage, 'comment')
0320ddc1 476
5dda1ede 477 def extract_list(meta_key):
d2d970d0 478 div = self._search_regex(
5dda1ede
S
479 r'(?s)<div[^>]+\bclass=["\'].*?\b%sWrapper[^>]*>(.+?)</div>'
480 % meta_key, webpage, meta_key, default=None)
d2d970d0 481 if div:
d0fb4bd1 482 return [clean_html(x).strip() for x in re.findall(r'(?s)<a[^>]+\bhref=[^>]+>.+?</a>', div)]
6bb05b32 483
cd85a1bb
S
484 info = self._search_json_ld(webpage, video_id, default={})
485 # description provided in JSON-LD is irrelevant
486 info['description'] = None
487
488 return merge_dicts({
125cfd78 489 'id': video_id,
490 'uploader': video_uploader,
3661ebf2 491 'upload_date': upload_date,
6c376029 492 'title': title,
125cfd78 493 'thumbnail': thumbnail,
ed8648a3 494 'duration': duration,
0320ddc1
S
495 'view_count': view_count,
496 'like_count': like_count,
497 'dislike_count': dislike_count,
498 'comment_count': comment_count,
79367a98 499 'formats': formats,
750e9833 500 'age_limit': 18,
5dda1ede
S
501 'tags': extract_list('tags'),
502 'categories': extract_list('categories'),
d0fb4bd1 503 'cast': extract_list('pornstars'),
4938c8d5 504 'subtitles': subtitles,
cd85a1bb 505 }, info)
e66e1a00
S
506
507
71a1f617 508class PornHubPlaylistBaseIE(PornHubBaseIE):
2181983a 509 def _extract_page(self, url):
510 return int_or_none(self._search_regex(
511 r'\bpage=(\d+)', url, 'page', default=None))
512
3430ff9b 513 def _extract_entries(self, webpage, host):
475bcb22
S
514 # Only process container div with main playlist content skipping
515 # drop-down menu that uses similar pattern for videos (see
067aa17e 516 # https://github.com/ytdl-org/youtube-dl/issues/11594).
475bcb22
S
517 container = self._search_regex(
518 r'(?s)(<div[^>]+class=["\']container.+)', webpage,
519 'container', default=webpage)
520
40e146aa 521 return [
3a23bae9 522 self.url_result(
3430ff9b 523 'http://www.%s/%s' % (host, video_url),
3a23bae9
S
524 PornHubIE.ie_key(), video_title=title)
525 for video_url, title in orderedSet(re.findall(
526 r'href="/?(view_video\.php\?.*\bviewkey=[\da-z]+[^"]*)"[^>]*\s+title="([^"]+)"',
475bcb22 527 container))
40e146aa 528 ]
e66e1a00 529
40e146aa 530
21b08463 531class PornHubUserIE(PornHubPlaylistBaseIE):
ed807c18 532 _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?%s/(?:(?:user|channel)s|model|pornstar)/(?P<id>[^/?#&]+))(?:[?#&]|/(?!videos)|$)' % PornHubBaseIE._PORNHUB_HOST_RE
40e146aa 533 _TESTS = [{
21b08463
S
534 'url': 'https://www.pornhub.com/model/zoe_ph',
535 'playlist_mincount': 118,
536 }, {
537 'url': 'https://www.pornhub.com/pornstar/liz-vicious',
40e146aa 538 'info_dict': {
21b08463 539 'id': 'liz-vicious',
40e146aa 540 },
21b08463
S
541 'playlist_mincount': 118,
542 }, {
543 'url': 'https://www.pornhub.com/users/russianveet69',
9634de17 544 'only_matching': True,
21b08463
S
545 }, {
546 'url': 'https://www.pornhub.com/channels/povd',
9634de17
S
547 'only_matching': True,
548 }, {
549 'url': 'https://www.pornhub.com/model/zoe_ph?abc=1',
550 'only_matching': True,
2181983a 551 }, {
552 # Unavailable via /videos page, but available with direct pagination
553 # on pornstar page (see [1]), requires premium
554 # 1. https://github.com/ytdl-org/youtube-dl/issues/27853
555 'url': 'https://www.pornhubpremium.com/pornstar/sienna-west',
556 'only_matching': True,
557 }, {
558 # Same as before, multi page
559 'url': 'https://www.pornhubpremium.com/pornstar/lily-labeau',
560 'only_matching': True,
ed807c18 561 }, {
4c968755 562 'url': 'https://pornhubvybmsymdol4iibwgwtkpwmeyd6luq2gxajgjzfjvotyt5zhyd.onion/model/zoe_ph',
ed807c18 563 'only_matching': True,
21b08463
S
564 }]
565
21b08463 566 def _real_extract(self, url):
5ad28e7f 567 mobj = self._match_valid_url(url)
21b08463 568 user_id = mobj.group('id')
2181983a 569 videos_url = '%s/videos' % mobj.group('url')
570 page = self._extract_page(url)
571 if page:
572 videos_url = update_url_query(videos_url, {'page': page})
21b08463 573 return self.url_result(
2181983a 574 videos_url, ie=PornHubPagedVideoListIE.ie_key(), video_id=user_id)
21b08463
S
575
576
577class PornHubPagedPlaylistBaseIE(PornHubPlaylistBaseIE):
4bf568d3
S
578 @staticmethod
579 def _has_more(webpage):
580 return re.search(
581 r'''(?x)
582 <li[^>]+\bclass=["\']page_next|
583 <link[^>]+\brel=["\']next|
584 <button[^>]+\bid=["\']moreDataBtn
585 ''', webpage) is not None
586
2181983a 587 def _entries(self, url, host, item_id):
588 page = self._extract_page(url)
21b08463 589
2181983a 590 VIDEOS = '/videos'
591
592 def download_page(base_url, num, fallback=False):
593 note = 'Downloading page %d%s' % (num, ' (switch to fallback)' if fallback else '')
594 return self._download_webpage(
595 base_url, item_id, note, query={'page': num})
1f7a563a 596
2181983a 597 def is_404(e):
598 return isinstance(e.cause, compat_HTTPError) and e.cause.code == 404
599
600 base_url = url
601 has_page = page is not None
602 first_page = page if has_page else 1
603 for page_num in (first_page, ) if has_page else itertools.count(first_page):
21b08463 604 try:
2181983a 605 try:
606 webpage = download_page(base_url, page_num)
607 except ExtractorError as e:
608 # Some sources may not be available via /videos page,
609 # trying to fallback to main page pagination (see [1])
610 # 1. https://github.com/ytdl-org/youtube-dl/issues/27853
611 if is_404(e) and page_num == first_page and VIDEOS in base_url:
612 base_url = base_url.replace(VIDEOS, '')
613 webpage = download_page(base_url, page_num, fallback=True)
614 else:
615 raise
21b08463 616 except ExtractorError as e:
2181983a 617 if is_404(e) and page_num != first_page:
21b08463
S
618 break
619 raise
620 page_entries = self._extract_entries(webpage, host)
621 if not page_entries:
622 break
2181983a 623 for e in page_entries:
624 yield e
21b08463
S
625 if not self._has_more(webpage):
626 break
627
2181983a 628 def _real_extract(self, url):
5ad28e7f 629 mobj = self._match_valid_url(url)
2181983a 630 host = mobj.group('host')
631 item_id = mobj.group('id')
632
633 self._login(host)
634
635 return self.playlist_result(self._entries(url, host, item_id), item_id)
21b08463
S
636
637
9634de17 638class PornHubPagedVideoListIE(PornHubPagedPlaylistBaseIE):
df2a5633 639 _VALID_URL = r'https?://(?:[^/]+\.)?%s/(?!playlist/)(?P<id>(?:[^/]+/)*[^/?#&]+)' % PornHubBaseIE._PORNHUB_HOST_RE
21b08463 640 _TESTS = [{
1f7a563a 641 'url': 'https://www.pornhub.com/model/zoe_ph/videos',
21b08463 642 'only_matching': True,
34541395
S
643 }, {
644 'url': 'http://www.pornhub.com/users/rushandlia/videos',
645 'only_matching': True,
21b08463
S
646 }, {
647 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos',
648 'info_dict': {
9634de17 649 'id': 'pornstar/jenny-blighe/videos',
21b08463
S
650 },
651 'playlist_mincount': 149,
1f7a563a
S
652 }, {
653 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos?page=3',
654 'info_dict': {
9634de17 655 'id': 'pornstar/jenny-blighe/videos',
1f7a563a
S
656 },
657 'playlist_mincount': 40,
f66df20c
PV
658 }, {
659 # default sorting as Top Rated Videos
660 'url': 'https://www.pornhub.com/channels/povd/videos',
661 'info_dict': {
9634de17 662 'id': 'channels/povd/videos',
f66df20c
PV
663 },
664 'playlist_mincount': 293,
665 }, {
666 # Top Rated Videos
667 'url': 'https://www.pornhub.com/channels/povd/videos?o=ra',
668 'only_matching': True,
669 }, {
670 # Most Recent Videos
671 'url': 'https://www.pornhub.com/channels/povd/videos?o=da',
672 'only_matching': True,
673 }, {
674 # Most Viewed Videos
675 'url': 'https://www.pornhub.com/channels/povd/videos?o=vi',
676 'only_matching': True,
92ded33a
S
677 }, {
678 'url': 'http://www.pornhub.com/users/zoe_ph/videos/public',
679 'only_matching': True,
21b08463
S
680 }, {
681 # Most Viewed Videos
682 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=mv',
683 'only_matching': True,
684 }, {
685 # Top Rated Videos
686 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=tr',
687 'only_matching': True,
688 }, {
689 # Longest Videos
690 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=lg',
691 'only_matching': True,
692 }, {
693 # Newest Videos
694 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=cm',
695 'only_matching': True,
21b08463
S
696 }, {
697 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos/paid',
698 'only_matching': True,
699 }, {
700 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos/fanonly',
701 'only_matching': True,
9634de17
S
702 }, {
703 'url': 'https://www.pornhub.com/video',
704 'only_matching': True,
705 }, {
706 'url': 'https://www.pornhub.com/video?page=3',
707 'only_matching': True,
708 }, {
709 'url': 'https://www.pornhub.com/video/search?search=123',
710 'only_matching': True,
711 }, {
712 'url': 'https://www.pornhub.com/categories/teen',
713 'only_matching': True,
714 }, {
715 'url': 'https://www.pornhub.com/categories/teen?page=3',
716 'only_matching': True,
717 }, {
718 'url': 'https://www.pornhub.com/hd',
719 'only_matching': True,
720 }, {
721 'url': 'https://www.pornhub.com/hd?page=3',
722 'only_matching': True,
723 }, {
724 'url': 'https://www.pornhub.com/described-video',
725 'only_matching': True,
726 }, {
727 'url': 'https://www.pornhub.com/described-video?page=2',
728 'only_matching': True,
729 }, {
730 'url': 'https://www.pornhub.com/video/incategories/60fps-1/hd-porn',
731 'only_matching': True,
ed807c18 732 }, {
4c968755 733 'url': 'https://pornhubvybmsymdol4iibwgwtkpwmeyd6luq2gxajgjzfjvotyt5zhyd.onion/model/zoe_ph/videos',
ed807c18 734 'only_matching': True,
40e146aa
S
735 }]
736
21b08463
S
737 @classmethod
738 def suitable(cls, url):
739 return (False
9634de17
S
740 if PornHubIE.suitable(url) or PornHubUserIE.suitable(url) or PornHubUserVideosUploadIE.suitable(url)
741 else super(PornHubPagedVideoListIE, cls).suitable(url))
21b08463 742
34541395 743
21b08463 744class PornHubUserVideosUploadIE(PornHubPagedPlaylistBaseIE):
ed807c18 745 _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?%s/(?:(?:user|channel)s|model|pornstar)/(?P<id>[^/]+)/videos/upload)' % PornHubBaseIE._PORNHUB_HOST_RE
21b08463
S
746 _TESTS = [{
747 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos/upload',
748 'info_dict': {
749 'id': 'jenny-blighe',
750 },
751 'playlist_mincount': 129,
752 }, {
753 'url': 'https://www.pornhub.com/model/zoe_ph/videos/upload',
754 'only_matching': True,
ed807c18 755 }, {
4c968755 756 'url': 'http://pornhubvybmsymdol4iibwgwtkpwmeyd6luq2gxajgjzfjvotyt5zhyd.onion/pornstar/jenny-blighe/videos/upload',
ed807c18 757 'only_matching': True,
21b08463 758 }]
df2a5633 759
760
761class PornHubPlaylistIE(PornHubPlaylistBaseIE):
762 _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?%s/playlist/(?P<id>[^/?#&]+))' % PornHubBaseIE._PORNHUB_HOST_RE
763 _TESTS = [{
764 'url': 'https://www.pornhub.com/playlist/44121572',
765 'info_dict': {
766 'id': '44121572',
767 },
768 'playlist_count': 77,
769 }, {
770 'url': 'https://www.pornhub.com/playlist/4667351',
771 'only_matching': True,
772 }, {
773 'url': 'https://de.pornhub.com/playlist/4667351',
774 'only_matching': True,
775 }, {
776 'url': 'https://de.pornhub.com/playlist/4667351?page=2',
777 'only_matching': True,
778 }]
779
780 def _entries(self, url, host, item_id):
781 webpage = self._download_webpage(url, item_id, 'Downloading page 1')
782 playlist_id = self._search_regex(r'var\s+playlistId\s*=\s*"([^"]+)"', webpage, 'playlist_id')
783 video_count = int_or_none(
784 self._search_regex(r'var\s+itemsCount\s*=\s*([0-9]+)\s*\|\|', webpage, 'video_count'))
785 token = self._search_regex(r'var\s+token\s*=\s*"([^"]+)"', webpage, 'token')
786 page_count = math.ceil((video_count - 36) / 40.) + 1
787 page_entries = self._extract_entries(webpage, host)
788
789 def download_page(page_num):
790 note = 'Downloading page {}'.format(page_num)
791 page_url = 'https://www.{}/playlist/viewChunked'.format(host)
792 return self._download_webpage(page_url, item_id, note, query={
793 'id': playlist_id,
794 'page': page_num,
795 'token': token,
796 })
797
798 for page_num in range(1, page_count + 1):
799 if page_num > 1:
800 webpage = download_page(page_num)
801 page_entries = self._extract_entries(webpage, host)
802 if not page_entries:
803 break
804 for e in page_entries:
805 yield e
806
807 def _real_extract(self, url):
5ad28e7f 808 mobj = self._match_valid_url(url)
df2a5633 809 host = mobj.group('host')
810 item_id = mobj.group('id')
811
812 self._login(host)
813
814 return self.playlist_result(self._entries(mobj.group('url'), host, item_id), item_id)