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