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