]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/pornhub.py
Update to ytdl-2021.01.03
[yt-dlp.git] / youtube_dlc / extractor / pornhub.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import functools
5 import itertools
6 import operator
7 import re
8
9 from .common import InfoExtractor
10 from ..compat import (
11 compat_HTTPError,
12 compat_str,
13 compat_urllib_request,
14 )
15 from .openload import PhantomJSwrapper
16 from ..utils import (
17 determine_ext,
18 ExtractorError,
19 int_or_none,
20 merge_dicts,
21 NO_DEFAULT,
22 orderedSet,
23 remove_quotes,
24 str_to_int,
25 url_or_none,
26 )
27
28
29 class PornHubBaseIE(InfoExtractor):
30 def _download_webpage_handle(self, *args, **kwargs):
31 def dl(*args, **kwargs):
32 return super(PornHubBaseIE, self)._download_webpage_handle(*args, **kwargs)
33
34 ret = dl(*args, **kwargs)
35
36 if not ret:
37 return ret
38
39 webpage, urlh = ret
40
41 if any(re.search(p, webpage) for p in (
42 r'<body\b[^>]+\bonload=["\']go\(\)',
43 r'document\.cookie\s*=\s*["\']RNKEY=',
44 r'document\.location\.reload\(true\)')):
45 url_or_request = args[0]
46 url = (url_or_request.get_full_url()
47 if isinstance(url_or_request, compat_urllib_request.Request)
48 else url_or_request)
49 phantom = PhantomJSwrapper(self, required_version='2.0')
50 phantom.get(url, html=webpage)
51 webpage, urlh = dl(*args, **kwargs)
52
53 return webpage, urlh
54
55
56 class PornHubIE(PornHubBaseIE):
57 IE_DESC = 'PornHub and Thumbzilla'
58 _VALID_URL = r'''(?x)
59 https?://
60 (?:
61 (?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?:(?:view_video\.php|video/show)\?viewkey=|embed/)|
62 (?:www\.)?thumbzilla\.com/video/
63 )
64 (?P<id>[\da-z]+)
65 '''
66 _TESTS = [{
67 'url': 'http://www.pornhub.com/view_video.php?viewkey=648719015',
68 'md5': 'a6391306d050e4547f62b3f485dd9ba9',
69 'info_dict': {
70 'id': '648719015',
71 'ext': 'mp4',
72 'title': 'Seductive Indian beauty strips down and fingers her pink pussy',
73 'uploader': 'Babes',
74 'upload_date': '20130628',
75 'timestamp': 1372447216,
76 'duration': 361,
77 'view_count': int,
78 'like_count': int,
79 'dislike_count': int,
80 'comment_count': int,
81 'age_limit': 18,
82 'tags': list,
83 'categories': list,
84 },
85 }, {
86 # non-ASCII title
87 'url': 'http://www.pornhub.com/view_video.php?viewkey=1331683002',
88 'info_dict': {
89 'id': '1331683002',
90 'ext': 'mp4',
91 'title': '重庆婷婷女王足交',
92 'upload_date': '20150213',
93 'timestamp': 1423804862,
94 'duration': 1753,
95 'view_count': int,
96 'like_count': int,
97 'dislike_count': int,
98 'comment_count': int,
99 'age_limit': 18,
100 'tags': list,
101 'categories': list,
102 },
103 'params': {
104 'skip_download': True,
105 },
106 }, {
107 # subtitles
108 'url': 'https://www.pornhub.com/view_video.php?viewkey=ph5af5fef7c2aa7',
109 'info_dict': {
110 'id': 'ph5af5fef7c2aa7',
111 'ext': 'mp4',
112 'title': 'BFFS - Cute Teen Girls Share Cock On the Floor',
113 'uploader': 'BFFs',
114 'duration': 622,
115 'view_count': int,
116 'like_count': int,
117 'dislike_count': int,
118 'comment_count': int,
119 'age_limit': 18,
120 'tags': list,
121 'categories': list,
122 'subtitles': {
123 'en': [{
124 "ext": 'srt'
125 }]
126 },
127 },
128 'params': {
129 'skip_download': True,
130 },
131 'skip': 'This video has been disabled',
132 }, {
133 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph557bbb6676d2d',
134 'only_matching': True,
135 }, {
136 # removed at the request of cam4.com
137 'url': 'http://fr.pornhub.com/view_video.php?viewkey=ph55ca2f9760862',
138 'only_matching': True,
139 }, {
140 # removed at the request of the copyright owner
141 'url': 'http://www.pornhub.com/view_video.php?viewkey=788152859',
142 'only_matching': True,
143 }, {
144 # removed by uploader
145 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph572716d15a111',
146 'only_matching': True,
147 }, {
148 # private video
149 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph56fd731fce6b7',
150 'only_matching': True,
151 }, {
152 'url': 'https://www.thumbzilla.com/video/ph56c6114abd99a/horny-girlfriend-sex',
153 'only_matching': True,
154 }, {
155 'url': 'http://www.pornhub.com/video/show?viewkey=648719015',
156 'only_matching': True,
157 }, {
158 'url': 'https://www.pornhub.net/view_video.php?viewkey=203640933',
159 'only_matching': True,
160 }, {
161 'url': 'https://www.pornhub.org/view_video.php?viewkey=203640933',
162 'only_matching': True,
163 }, {
164 'url': 'https://www.pornhubpremium.com/view_video.php?viewkey=ph5e4acdae54a82',
165 'only_matching': True,
166 }]
167
168 @staticmethod
169 def _extract_urls(webpage):
170 return re.findall(
171 r'<iframe[^>]+?src=["\'](?P<url>(?:https?:)?//(?:www\.)?pornhub\.(?:com|net|org)/embed/[\da-z]+)',
172 webpage)
173
174 def _extract_count(self, pattern, webpage, name):
175 return str_to_int(self._search_regex(
176 pattern, webpage, '%s count' % name, fatal=False))
177
178 def _real_extract(self, url):
179 mobj = re.match(self._VALID_URL, url)
180 host = mobj.group('host') or 'pornhub.com'
181 video_id = mobj.group('id')
182
183 if 'premium' in host:
184 if not self._downloader.params.get('cookiefile'):
185 raise ExtractorError(
186 'PornHub Premium requires authentication.'
187 ' You may want to use --cookies.',
188 expected=True)
189
190 self._set_cookie(host, 'age_verified', '1')
191
192 def dl_webpage(platform):
193 self._set_cookie(host, 'platform', platform)
194 return self._download_webpage(
195 'https://www.%s/view_video.php?viewkey=%s' % (host, video_id),
196 video_id, 'Downloading %s webpage' % platform)
197
198 webpage = dl_webpage('pc')
199
200 error_msg = self._html_search_regex(
201 r'(?s)<div[^>]+class=(["\'])(?:(?!\1).)*\b(?:removed|userMessageSection)\b(?:(?!\1).)*\1[^>]*>(?P<error>.+?)</div>',
202 webpage, 'error message', default=None, group='error')
203 if error_msg:
204 error_msg = re.sub(r'\s+', ' ', error_msg)
205 raise ExtractorError(
206 'PornHub said: %s' % error_msg,
207 expected=True, video_id=video_id)
208
209 # video_title from flashvars contains whitespace instead of non-ASCII (see
210 # http://www.pornhub.com/view_video.php?viewkey=1331683002), not relying
211 # on that anymore.
212 title = self._html_search_meta(
213 'twitter:title', webpage, default=None) or self._html_search_regex(
214 (r'(?s)<h1[^>]+class=["\']title["\'][^>]*>(?P<title>.+?)</h1>',
215 r'<div[^>]+data-video-title=(["\'])(?P<title>(?:(?!\1).)+)\1',
216 r'shareTitle["\']\s*[=:]\s*(["\'])(?P<title>(?:(?!\1).)+)\1'),
217 webpage, 'title', group='title')
218
219 video_urls = []
220 video_urls_set = set()
221 subtitles = {}
222
223 flashvars = self._parse_json(
224 self._search_regex(
225 r'var\s+flashvars_\d+\s*=\s*({.+?});', webpage, 'flashvars', default='{}'),
226 video_id)
227 if flashvars:
228 subtitle_url = url_or_none(flashvars.get('closedCaptionsFile'))
229 if subtitle_url:
230 subtitles.setdefault('en', []).append({
231 'url': subtitle_url,
232 'ext': 'srt',
233 })
234 thumbnail = flashvars.get('image_url')
235 duration = int_or_none(flashvars.get('video_duration'))
236 media_definitions = flashvars.get('mediaDefinitions')
237 if isinstance(media_definitions, list):
238 for definition in media_definitions:
239 if not isinstance(definition, dict):
240 continue
241 video_url = definition.get('videoUrl')
242 if not video_url or not isinstance(video_url, compat_str):
243 continue
244 if video_url in video_urls_set:
245 continue
246 video_urls_set.add(video_url)
247 video_urls.append(
248 (video_url, int_or_none(definition.get('quality'))))
249 else:
250 thumbnail, duration = [None] * 2
251
252 def extract_js_vars(webpage, pattern, default=NO_DEFAULT):
253 assignments = self._search_regex(
254 pattern, webpage, 'encoded url', default=default)
255 if not assignments:
256 return {}
257
258 assignments = assignments.split(';')
259
260 js_vars = {}
261
262 def parse_js_value(inp):
263 inp = re.sub(r'/\*(?:(?!\*/).)*?\*/', '', inp)
264 if '+' in inp:
265 inps = inp.split('+')
266 return functools.reduce(
267 operator.concat, map(parse_js_value, inps))
268 inp = inp.strip()
269 if inp in js_vars:
270 return js_vars[inp]
271 return remove_quotes(inp)
272
273 for assn in assignments:
274 assn = assn.strip()
275 if not assn:
276 continue
277 assn = re.sub(r'var\s+', '', assn)
278 vname, value = assn.split('=', 1)
279 js_vars[vname] = parse_js_value(value)
280 return js_vars
281
282 def add_video_url(video_url):
283 v_url = url_or_none(video_url)
284 if not v_url:
285 return
286 if v_url in video_urls_set:
287 return
288 video_urls.append((v_url, None))
289 video_urls_set.add(v_url)
290
291 def parse_quality_items(quality_items):
292 q_items = self._parse_json(quality_items, video_id, fatal=False)
293 if not isinstance(q_items, list):
294 return
295 for item in q_items:
296 if isinstance(item, dict):
297 add_video_url(item.get('url'))
298
299 if not video_urls:
300 FORMAT_PREFIXES = ('media', 'quality', 'qualityItems')
301 js_vars = extract_js_vars(
302 webpage, r'(var\s+(?:%s)_.+)' % '|'.join(FORMAT_PREFIXES),
303 default=None)
304 if js_vars:
305 for key, format_url in js_vars.items():
306 if key.startswith(FORMAT_PREFIXES[-1]):
307 parse_quality_items(format_url)
308 elif any(key.startswith(p) for p in FORMAT_PREFIXES[:2]):
309 add_video_url(format_url)
310 if not video_urls and re.search(
311 r'<[^>]+\bid=["\']lockedPlayer', webpage):
312 raise ExtractorError(
313 'Video %s is locked' % video_id, expected=True)
314
315 if not video_urls:
316 js_vars = extract_js_vars(
317 dl_webpage('tv'), r'(var.+?mediastring.+?)</script>')
318 add_video_url(js_vars['mediastring'])
319
320 for mobj in re.finditer(
321 r'<a[^>]+\bclass=["\']downloadBtn\b[^>]+\bhref=(["\'])(?P<url>(?:(?!\1).)+)\1',
322 webpage):
323 video_url = mobj.group('url')
324 if video_url not in video_urls_set:
325 video_urls.append((video_url, None))
326 video_urls_set.add(video_url)
327
328 upload_date = None
329 formats = []
330 for video_url, height in video_urls:
331 if not upload_date:
332 upload_date = self._search_regex(
333 r'/(\d{6}/\d{2})/', video_url, 'upload data', default=None)
334 if upload_date:
335 upload_date = upload_date.replace('/', '')
336 ext = determine_ext(video_url)
337 if ext == 'mpd':
338 formats.extend(self._extract_mpd_formats(
339 video_url, video_id, mpd_id='dash', fatal=False))
340 continue
341 elif ext == 'm3u8':
342 formats.extend(self._extract_m3u8_formats(
343 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
344 m3u8_id='hls', fatal=False))
345 continue
346 tbr = None
347 mobj = re.search(r'(?P<height>\d+)[pP]?_(?P<tbr>\d+)[kK]', video_url)
348 if mobj:
349 if not height:
350 height = int(mobj.group('height'))
351 tbr = int(mobj.group('tbr'))
352 formats.append({
353 'url': video_url,
354 'format_id': '%dp' % height if height else None,
355 'height': height,
356 'tbr': tbr,
357 })
358 self._sort_formats(formats)
359
360 video_uploader = self._html_search_regex(
361 r'(?s)From:&nbsp;.+?<(?:a\b[^>]+\bhref=["\']/(?:(?:user|channel)s|model|pornstar)/|span\b[^>]+\bclass=["\']username)[^>]+>(.+?)<',
362 webpage, 'uploader', default=None)
363
364 def extract_vote_count(kind, name):
365 return self._extract_count(
366 (r'<span[^>]+\bclass="votes%s"[^>]*>([\d,\.]+)</span>' % kind,
367 r'<span[^>]+\bclass=["\']votes%s["\'][^>]*\bdata-rating=["\'](\d+)' % kind),
368 webpage, name)
369
370 view_count = self._extract_count(
371 r'<span class="count">([\d,\.]+)</span> [Vv]iews', webpage, 'view')
372 like_count = extract_vote_count('Up', 'like')
373 dislike_count = extract_vote_count('Down', 'dislike')
374 comment_count = self._extract_count(
375 r'All Comments\s*<span>\(([\d,.]+)\)', webpage, 'comment')
376
377 def extract_list(meta_key):
378 div = self._search_regex(
379 r'(?s)<div[^>]+\bclass=["\'].*?\b%sWrapper[^>]*>(.+?)</div>'
380 % meta_key, webpage, meta_key, default=None)
381 if div:
382 return re.findall(r'<a[^>]+\bhref=[^>]+>([^<]+)', div)
383
384 info = self._search_json_ld(webpage, video_id, default={})
385 # description provided in JSON-LD is irrelevant
386 info['description'] = None
387
388 return merge_dicts({
389 'id': video_id,
390 'uploader': video_uploader,
391 'upload_date': upload_date,
392 'title': title,
393 'thumbnail': thumbnail,
394 'duration': duration,
395 'view_count': view_count,
396 'like_count': like_count,
397 'dislike_count': dislike_count,
398 'comment_count': comment_count,
399 'formats': formats,
400 'age_limit': 18,
401 'tags': extract_list('tags'),
402 'categories': extract_list('categories'),
403 'subtitles': subtitles,
404 }, info)
405
406
407 class PornHubPlaylistBaseIE(PornHubBaseIE):
408 def _extract_entries(self, webpage, host):
409 # Only process container div with main playlist content skipping
410 # drop-down menu that uses similar pattern for videos (see
411 # https://github.com/ytdl-org/youtube-dl/issues/11594).
412 container = self._search_regex(
413 r'(?s)(<div[^>]+class=["\']container.+)', webpage,
414 'container', default=webpage)
415
416 return [
417 self.url_result(
418 'http://www.%s/%s' % (host, video_url),
419 PornHubIE.ie_key(), video_title=title)
420 for video_url, title in orderedSet(re.findall(
421 r'href="/?(view_video\.php\?.*\bviewkey=[\da-z]+[^"]*)"[^>]*\s+title="([^"]+)"',
422 container))
423 ]
424
425 def _real_extract(self, url):
426 mobj = re.match(self._VALID_URL, url)
427 host = mobj.group('host')
428 playlist_id = mobj.group('id')
429
430 webpage = self._download_webpage(url, playlist_id)
431
432 entries = self._extract_entries(webpage, host)
433
434 playlist = self._parse_json(
435 self._search_regex(
436 r'(?:playlistObject|PLAYLIST_VIEW)\s*=\s*({.+?});', webpage,
437 'playlist', default='{}'),
438 playlist_id, fatal=False)
439 title = playlist.get('title') or self._search_regex(
440 r'>Videos\s+in\s+(.+?)\s+[Pp]laylist<', webpage, 'title', fatal=False)
441
442 return self.playlist_result(
443 entries, playlist_id, title, playlist.get('description'))
444
445
446 class PornHubUserIE(PornHubPlaylistBaseIE):
447 _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?:(?:user|channel)s|model|pornstar)/(?P<id>[^/?#&]+))(?:[?#&]|/(?!videos)|$)'
448 _TESTS = [{
449 'url': 'https://www.pornhub.com/model/zoe_ph',
450 'playlist_mincount': 118,
451 }, {
452 'url': 'https://www.pornhub.com/pornstar/liz-vicious',
453 'info_dict': {
454 'id': 'liz-vicious',
455 },
456 'playlist_mincount': 118,
457 }, {
458 'url': 'https://www.pornhub.com/users/russianveet69',
459 'only_matching': True,
460 }, {
461 'url': 'https://www.pornhub.com/channels/povd',
462 'only_matching': True,
463 }, {
464 'url': 'https://www.pornhub.com/model/zoe_ph?abc=1',
465 'only_matching': True,
466 }]
467
468 def _real_extract(self, url):
469 mobj = re.match(self._VALID_URL, url)
470 user_id = mobj.group('id')
471 return self.url_result(
472 '%s/videos' % mobj.group('url'), ie=PornHubPagedVideoListIE.ie_key(),
473 video_id=user_id)
474
475
476 class PornHubPagedPlaylistBaseIE(PornHubPlaylistBaseIE):
477 @staticmethod
478 def _has_more(webpage):
479 return re.search(
480 r'''(?x)
481 <li[^>]+\bclass=["\']page_next|
482 <link[^>]+\brel=["\']next|
483 <button[^>]+\bid=["\']moreDataBtn
484 ''', webpage) is not None
485
486 def _real_extract(self, url):
487 mobj = re.match(self._VALID_URL, url)
488 host = mobj.group('host')
489 item_id = mobj.group('id')
490
491 page = int_or_none(self._search_regex(
492 r'\bpage=(\d+)', url, 'page', default=None))
493
494 entries = []
495 for page_num in (page, ) if page is not None else itertools.count(1):
496 try:
497 webpage = self._download_webpage(
498 url, item_id, 'Downloading page %d' % page_num,
499 query={'page': page_num})
500 except ExtractorError as e:
501 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
502 break
503 raise
504 page_entries = self._extract_entries(webpage, host)
505 if not page_entries:
506 break
507 entries.extend(page_entries)
508 if not self._has_more(webpage):
509 break
510
511 return self.playlist_result(orderedSet(entries), item_id)
512
513
514 class PornHubPagedVideoListIE(PornHubPagedPlaylistBaseIE):
515 _VALID_URL = r'https?://(?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?P<id>(?:[^/]+/)*[^/?#&]+)'
516 _TESTS = [{
517 'url': 'https://www.pornhub.com/model/zoe_ph/videos',
518 'only_matching': True,
519 }, {
520 'url': 'http://www.pornhub.com/users/rushandlia/videos',
521 'only_matching': True,
522 }, {
523 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos',
524 'info_dict': {
525 'id': 'pornstar/jenny-blighe/videos',
526 },
527 'playlist_mincount': 149,
528 }, {
529 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos?page=3',
530 'info_dict': {
531 'id': 'pornstar/jenny-blighe/videos',
532 },
533 'playlist_mincount': 40,
534 }, {
535 # default sorting as Top Rated Videos
536 'url': 'https://www.pornhub.com/channels/povd/videos',
537 'info_dict': {
538 'id': 'channels/povd/videos',
539 },
540 'playlist_mincount': 293,
541 }, {
542 # Top Rated Videos
543 'url': 'https://www.pornhub.com/channels/povd/videos?o=ra',
544 'only_matching': True,
545 }, {
546 # Most Recent Videos
547 'url': 'https://www.pornhub.com/channels/povd/videos?o=da',
548 'only_matching': True,
549 }, {
550 # Most Viewed Videos
551 'url': 'https://www.pornhub.com/channels/povd/videos?o=vi',
552 'only_matching': True,
553 }, {
554 'url': 'http://www.pornhub.com/users/zoe_ph/videos/public',
555 'only_matching': True,
556 }, {
557 # Most Viewed Videos
558 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=mv',
559 'only_matching': True,
560 }, {
561 # Top Rated Videos
562 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=tr',
563 'only_matching': True,
564 }, {
565 # Longest Videos
566 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=lg',
567 'only_matching': True,
568 }, {
569 # Newest Videos
570 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=cm',
571 'only_matching': True,
572 }, {
573 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos/paid',
574 'only_matching': True,
575 }, {
576 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos/fanonly',
577 'only_matching': True,
578 }, {
579 'url': 'https://www.pornhub.com/video',
580 'only_matching': True,
581 }, {
582 'url': 'https://www.pornhub.com/video?page=3',
583 'only_matching': True,
584 }, {
585 'url': 'https://www.pornhub.com/video/search?search=123',
586 'only_matching': True,
587 }, {
588 'url': 'https://www.pornhub.com/categories/teen',
589 'only_matching': True,
590 }, {
591 'url': 'https://www.pornhub.com/categories/teen?page=3',
592 'only_matching': True,
593 }, {
594 'url': 'https://www.pornhub.com/hd',
595 'only_matching': True,
596 }, {
597 'url': 'https://www.pornhub.com/hd?page=3',
598 'only_matching': True,
599 }, {
600 'url': 'https://www.pornhub.com/described-video',
601 'only_matching': True,
602 }, {
603 'url': 'https://www.pornhub.com/described-video?page=2',
604 'only_matching': True,
605 }, {
606 'url': 'https://www.pornhub.com/video/incategories/60fps-1/hd-porn',
607 'only_matching': True,
608 }, {
609 'url': 'https://www.pornhub.com/playlist/44121572',
610 'info_dict': {
611 'id': 'playlist/44121572',
612 },
613 'playlist_mincount': 132,
614 }, {
615 'url': 'https://www.pornhub.com/playlist/4667351',
616 'only_matching': True,
617 }, {
618 'url': 'https://de.pornhub.com/playlist/4667351',
619 'only_matching': True,
620 }]
621
622 @classmethod
623 def suitable(cls, url):
624 return (False
625 if PornHubIE.suitable(url) or PornHubUserIE.suitable(url) or PornHubUserVideosUploadIE.suitable(url)
626 else super(PornHubPagedVideoListIE, cls).suitable(url))
627
628
629 class PornHubUserVideosUploadIE(PornHubPagedPlaylistBaseIE):
630 _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?:(?:user|channel)s|model|pornstar)/(?P<id>[^/]+)/videos/upload)'
631 _TESTS = [{
632 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos/upload',
633 'info_dict': {
634 'id': 'jenny-blighe',
635 },
636 'playlist_mincount': 129,
637 }, {
638 'url': 'https://www.pornhub.com/model/zoe_ph/videos/upload',
639 'only_matching': True,
640 }]