[pornhub] Extract categories and tags (closes #10499)
[youtube-dl] / youtube_dl / extractor / pornhub.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import os
6 import re
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_HTTPError,
11     compat_urllib_parse_unquote,
12     compat_urllib_parse_unquote_plus,
13     compat_urllib_parse_urlparse,
14 )
15 from ..utils import (
16     ExtractorError,
17     int_or_none,
18     js_to_json,
19     orderedSet,
20     sanitized_Request,
21     str_to_int,
22 )
23 from ..aes import (
24     aes_decrypt_text
25 )
26
27
28 class PornHubIE(InfoExtractor):
29     IE_DESC = 'PornHub and Thumbzilla'
30     _VALID_URL = r'''(?x)
31                     https?://
32                         (?:
33                             (?:[a-z]+\.)?pornhub\.com/(?:view_video\.php\?viewkey=|embed/)|
34                             (?:www\.)?thumbzilla\.com/video/
35                         )
36                         (?P<id>[0-9a-z]+)
37                     '''
38     _TESTS = [{
39         'url': 'http://www.pornhub.com/view_video.php?viewkey=648719015',
40         'md5': '1e19b41231a02eba417839222ac9d58e',
41         'info_dict': {
42             'id': '648719015',
43             'ext': 'mp4',
44             'title': 'Seductive Indian beauty strips down and fingers her pink pussy',
45             'uploader': 'Babes',
46             'duration': 361,
47             'view_count': int,
48             'like_count': int,
49             'dislike_count': int,
50             'comment_count': int,
51             'age_limit': 18,
52             'tags': list,
53             'categories': list,
54         },
55     }, {
56         # non-ASCII title
57         'url': 'http://www.pornhub.com/view_video.php?viewkey=1331683002',
58         'info_dict': {
59             'id': '1331683002',
60             'ext': 'mp4',
61             'title': '重庆婷婷女王足交',
62             'uploader': 'cj397186295',
63             'duration': 1753,
64             'view_count': int,
65             'like_count': int,
66             'dislike_count': int,
67             'comment_count': int,
68             'age_limit': 18,
69             'tags': list,
70             'categories': list,
71         },
72         'params': {
73             'skip_download': True,
74         },
75     }, {
76         'url': 'http://www.pornhub.com/view_video.php?viewkey=ph557bbb6676d2d',
77         'only_matching': True,
78     }, {
79         # removed at the request of cam4.com
80         'url': 'http://fr.pornhub.com/view_video.php?viewkey=ph55ca2f9760862',
81         'only_matching': True,
82     }, {
83         # removed at the request of the copyright owner
84         'url': 'http://www.pornhub.com/view_video.php?viewkey=788152859',
85         'only_matching': True,
86     }, {
87         # removed by uploader
88         'url': 'http://www.pornhub.com/view_video.php?viewkey=ph572716d15a111',
89         'only_matching': True,
90     }, {
91         # private video
92         'url': 'http://www.pornhub.com/view_video.php?viewkey=ph56fd731fce6b7',
93         'only_matching': True,
94     }, {
95         'url': 'https://www.thumbzilla.com/video/ph56c6114abd99a/horny-girlfriend-sex',
96         'only_matching': True,
97     }]
98
99     @classmethod
100     def _extract_url(cls, webpage):
101         mobj = re.search(
102             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?pornhub\.com/embed/\d+)\1', webpage)
103         if mobj:
104             return mobj.group('url')
105
106     def _extract_count(self, pattern, webpage, name):
107         return str_to_int(self._search_regex(
108             pattern, webpage, '%s count' % name, fatal=False))
109
110     def _real_extract(self, url):
111         video_id = self._match_id(url)
112
113         req = sanitized_Request(
114             'http://www.pornhub.com/view_video.php?viewkey=%s' % video_id)
115         req.add_header('Cookie', 'age_verified=1')
116         webpage = self._download_webpage(req, video_id)
117
118         error_msg = self._html_search_regex(
119             r'(?s)<div[^>]+class=(["\'])(?:(?!\1).)*\b(?:removed|userMessageSection)\b(?:(?!\1).)*\1[^>]*>(?P<error>.+?)</div>',
120             webpage, 'error message', default=None, group='error')
121         if error_msg:
122             error_msg = re.sub(r'\s+', ' ', error_msg)
123             raise ExtractorError(
124                 'PornHub said: %s' % error_msg,
125                 expected=True, video_id=video_id)
126
127         # video_title from flashvars contains whitespace instead of non-ASCII (see
128         # http://www.pornhub.com/view_video.php?viewkey=1331683002), not relying
129         # on that anymore.
130         title = self._html_search_meta(
131             'twitter:title', webpage, default=None) or self._search_regex(
132             (r'<h1[^>]+class=["\']title["\'][^>]*>(?P<title>[^<]+)',
133              r'<div[^>]+data-video-title=(["\'])(?P<title>.+?)\1',
134              r'shareTitle\s*=\s*(["\'])(?P<title>.+?)\1'),
135             webpage, 'title', group='title')
136
137         flashvars = self._parse_json(
138             self._search_regex(
139                 r'var\s+flashvars_\d+\s*=\s*({.+?});', webpage, 'flashvars', default='{}'),
140             video_id)
141         if flashvars:
142             thumbnail = flashvars.get('image_url')
143             duration = int_or_none(flashvars.get('video_duration'))
144         else:
145             title, thumbnail, duration = [None] * 3
146
147         video_uploader = self._html_search_regex(
148             r'(?s)From:&nbsp;.+?<(?:a href="/users/|a href="/channels/|span class="username)[^>]+>(.+?)<',
149             webpage, 'uploader', fatal=False)
150
151         view_count = self._extract_count(
152             r'<span class="count">([\d,\.]+)</span> views', webpage, 'view')
153         like_count = self._extract_count(
154             r'<span class="votesUp">([\d,\.]+)</span>', webpage, 'like')
155         dislike_count = self._extract_count(
156             r'<span class="votesDown">([\d,\.]+)</span>', webpage, 'dislike')
157         comment_count = self._extract_count(
158             r'All Comments\s*<span>\(([\d,.]+)\)', webpage, 'comment')
159
160         video_urls = list(map(compat_urllib_parse_unquote, re.findall(r"player_quality_[0-9]{3}p\s*=\s*'([^']+)'", webpage)))
161         if webpage.find('"encrypted":true') != -1:
162             password = compat_urllib_parse_unquote_plus(
163                 self._search_regex(r'"video_title":"([^"]+)', webpage, 'password'))
164             video_urls = list(map(lambda s: aes_decrypt_text(s, password, 32).decode('utf-8'), video_urls))
165
166         formats = []
167         for video_url in video_urls:
168             path = compat_urllib_parse_urlparse(video_url).path
169             extension = os.path.splitext(path)[1][1:]
170             format = path.split('/')[5].split('_')[:2]
171             format = '-'.join(format)
172
173             m = re.match(r'^(?P<height>[0-9]+)[pP]-(?P<tbr>[0-9]+)[kK]$', format)
174             if m is None:
175                 height = None
176                 tbr = None
177             else:
178                 height = int(m.group('height'))
179                 tbr = int(m.group('tbr'))
180
181             formats.append({
182                 'url': video_url,
183                 'ext': extension,
184                 'format': format,
185                 'format_id': format,
186                 'tbr': tbr,
187                 'height': height,
188             })
189         self._sort_formats(formats)
190
191         page_params = self._parse_json(self._search_regex(
192             r'page_params\.zoneDetails\[([\'"])[^\'"]+\1\]\s*=\s*(?P<data>{[^}]+})',
193             webpage, 'page parameters', group='data', default='{}'),
194             video_id, transform_source=js_to_json, fatal=False)
195         tags = categories = None
196         if page_params:
197             tags = page_params.get('tags', '').split(',')
198             categories = page_params.get('categories', '').split(',')
199
200         return {
201             'id': video_id,
202             'uploader': video_uploader,
203             'title': title,
204             'thumbnail': thumbnail,
205             'duration': duration,
206             'view_count': view_count,
207             'like_count': like_count,
208             'dislike_count': dislike_count,
209             'comment_count': comment_count,
210             'formats': formats,
211             'age_limit': 18,
212             'tags': tags,
213             'categories': categories,
214         }
215
216
217 class PornHubPlaylistBaseIE(InfoExtractor):
218     def _extract_entries(self, webpage):
219         return [
220             self.url_result(
221                 'http://www.pornhub.com/%s' % video_url,
222                 PornHubIE.ie_key(), video_title=title)
223             for video_url, title in orderedSet(re.findall(
224                 r'href="/?(view_video\.php\?.*\bviewkey=[\da-z]+[^"]*)"[^>]*\s+title="([^"]+)"',
225                 webpage))
226         ]
227
228     def _real_extract(self, url):
229         playlist_id = self._match_id(url)
230
231         webpage = self._download_webpage(url, playlist_id)
232
233         entries = self._extract_entries(webpage)
234
235         playlist = self._parse_json(
236             self._search_regex(
237                 r'playlistObject\s*=\s*({.+?});', webpage, 'playlist'),
238             playlist_id)
239
240         return self.playlist_result(
241             entries, playlist_id, playlist.get('title'), playlist.get('description'))
242
243
244 class PornHubPlaylistIE(PornHubPlaylistBaseIE):
245     _VALID_URL = r'https?://(?:www\.)?pornhub\.com/playlist/(?P<id>\d+)'
246     _TESTS = [{
247         'url': 'http://www.pornhub.com/playlist/6201671',
248         'info_dict': {
249             'id': '6201671',
250             'title': 'P0p4',
251         },
252         'playlist_mincount': 35,
253     }]
254
255
256 class PornHubUserVideosIE(PornHubPlaylistBaseIE):
257     _VALID_URL = r'https?://(?:www\.)?pornhub\.com/users/(?P<id>[^/]+)/videos'
258     _TESTS = [{
259         'url': 'http://www.pornhub.com/users/zoe_ph/videos/public',
260         'info_dict': {
261             'id': 'zoe_ph',
262         },
263         'playlist_mincount': 171,
264     }, {
265         'url': 'http://www.pornhub.com/users/rushandlia/videos',
266         'only_matching': True,
267     }]
268
269     def _real_extract(self, url):
270         user_id = self._match_id(url)
271
272         entries = []
273         for page_num in itertools.count(1):
274             try:
275                 webpage = self._download_webpage(
276                     url, user_id, 'Downloading page %d' % page_num,
277                     query={'page': page_num})
278             except ExtractorError as e:
279                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
280                     break
281             page_entries = self._extract_entries(webpage)
282             if not page_entries:
283                 break
284             entries.extend(page_entries)
285
286         return self.playlist_result(entries, user_id)