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