[pornhub] Extract video URL from tv platform site (#12007, #12129)
[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>[\da-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     @staticmethod
100     def _extract_urls(webpage):
101         return re.findall(
102             r'<iframe[^>]+?src=["\'](?P<url>(?:https?:)?//(?:www\.)?pornhub\.com/embed/[\da-z]+)',
103             webpage)
104
105     def _extract_count(self, pattern, webpage, name):
106         return str_to_int(self._search_regex(
107             pattern, webpage, '%s count' % name, fatal=False))
108
109     def _real_extract(self, url):
110         video_id = self._match_id(url)
111
112         def dl_webpage(platform):
113             return self._download_webpage(
114                 'http://www.pornhub.com/view_video.php?viewkey=%s' % video_id,
115                 video_id, headers={
116                     'Cookie': 'age_verified=1; platform=%s' % platform,
117                 })
118
119         webpage = dl_webpage('pc')
120
121         error_msg = self._html_search_regex(
122             r'(?s)<div[^>]+class=(["\'])(?:(?!\1).)*\b(?:removed|userMessageSection)\b(?:(?!\1).)*\1[^>]*>(?P<error>.+?)</div>',
123             webpage, 'error message', default=None, group='error')
124         if error_msg:
125             error_msg = re.sub(r'\s+', ' ', error_msg)
126             raise ExtractorError(
127                 'PornHub said: %s' % error_msg,
128                 expected=True, video_id=video_id)
129
130         tv_webpage = dl_webpage('tv')
131
132         video_url = self._search_regex(
133             r'<video[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//.+?)\1', tv_webpage,
134             'video url', group='url')
135
136         title = self._search_regex(
137             r'<h1>([^>]+)</h1>', tv_webpage, 'title', default=None)
138
139         # video_title from flashvars contains whitespace instead of non-ASCII (see
140         # http://www.pornhub.com/view_video.php?viewkey=1331683002), not relying
141         # on that anymore.
142         title = title or self._html_search_meta(
143             'twitter:title', webpage, default=None) or self._search_regex(
144             (r'<h1[^>]+class=["\']title["\'][^>]*>(?P<title>[^<]+)',
145              r'<div[^>]+data-video-title=(["\'])(?P<title>.+?)\1',
146              r'shareTitle\s*=\s*(["\'])(?P<title>.+?)\1'),
147             webpage, 'title', group='title')
148
149         flashvars = self._parse_json(
150             self._search_regex(
151                 r'var\s+flashvars_\d+\s*=\s*({.+?});', webpage, 'flashvars', default='{}'),
152             video_id)
153         if flashvars:
154             thumbnail = flashvars.get('image_url')
155             duration = int_or_none(flashvars.get('video_duration'))
156         else:
157             title, thumbnail, duration = [None] * 3
158
159         video_uploader = self._html_search_regex(
160             r'(?s)From:&nbsp;.+?<(?:a href="/users/|a href="/channels/|span class="username)[^>]+>(.+?)<',
161             webpage, 'uploader', fatal=False)
162
163         view_count = self._extract_count(
164             r'<span class="count">([\d,\.]+)</span> views', webpage, 'view')
165         like_count = self._extract_count(
166             r'<span class="votesUp">([\d,\.]+)</span>', webpage, 'like')
167         dislike_count = self._extract_count(
168             r'<span class="votesDown">([\d,\.]+)</span>', webpage, 'dislike')
169         comment_count = self._extract_count(
170             r'All Comments\s*<span>\(([\d,.]+)\)', webpage, 'comment')
171
172         """
173         video_variables = {}
174         for video_variablename, quote, video_variable in re.findall(
175                 r'(player_quality_[0-9]{3,4}p\w+)\s*=\s*(["\'])(.+?)\2;', webpage):
176             video_variables[video_variablename] = video_variable
177
178         video_urls = []
179         for encoded_video_url in re.findall(
180                 r'player_quality_[0-9]{3,4}p\s*=(.+?);', webpage):
181             for varname, varval in video_variables.items():
182                 encoded_video_url = encoded_video_url.replace(varname, varval)
183             video_urls.append(re.sub(r'[\s+]', '', encoded_video_url))
184
185         if webpage.find('"encrypted":true') != -1:
186             password = compat_urllib_parse_unquote_plus(
187                 self._search_regex(r'"video_title":"([^"]+)', webpage, 'password'))
188             video_urls = list(map(lambda s: aes_decrypt_text(s, password, 32).decode('utf-8'), video_urls))
189
190         formats = []
191         for video_url in video_urls:
192             path = compat_urllib_parse_urlparse(video_url).path
193             extension = os.path.splitext(path)[1][1:]
194             format = path.split('/')[5].split('_')[:2]
195             format = '-'.join(format)
196
197             m = re.match(r'^(?P<height>[0-9]+)[pP]-(?P<tbr>[0-9]+)[kK]$', format)
198             if m is None:
199                 height = None
200                 tbr = None
201             else:
202                 height = int(m.group('height'))
203                 tbr = int(m.group('tbr'))
204
205             formats.append({
206                 'url': video_url,
207                 'ext': extension,
208                 'format': format,
209                 'format_id': format,
210                 'tbr': tbr,
211                 'height': height,
212             })
213         self._sort_formats(formats)
214         """
215
216         page_params = self._parse_json(self._search_regex(
217             r'page_params\.zoneDetails\[([\'"])[^\'"]+\1\]\s*=\s*(?P<data>{[^}]+})',
218             webpage, 'page parameters', group='data', default='{}'),
219             video_id, transform_source=js_to_json, fatal=False)
220         tags = categories = None
221         if page_params:
222             tags = page_params.get('tags', '').split(',')
223             categories = page_params.get('categories', '').split(',')
224
225         return {
226             'id': video_id,
227             'url': video_url,
228             'uploader': video_uploader,
229             'title': title,
230             'thumbnail': thumbnail,
231             'duration': duration,
232             'view_count': view_count,
233             'like_count': like_count,
234             'dislike_count': dislike_count,
235             'comment_count': comment_count,
236             # 'formats': formats,
237             'age_limit': 18,
238             'tags': tags,
239             'categories': categories,
240         }
241
242
243 class PornHubPlaylistBaseIE(InfoExtractor):
244     def _extract_entries(self, webpage):
245         return [
246             self.url_result(
247                 'http://www.pornhub.com/%s' % video_url,
248                 PornHubIE.ie_key(), video_title=title)
249             for video_url, title in orderedSet(re.findall(
250                 r'href="/?(view_video\.php\?.*\bviewkey=[\da-z]+[^"]*)"[^>]*\s+title="([^"]+)"',
251                 webpage))
252         ]
253
254     def _real_extract(self, url):
255         playlist_id = self._match_id(url)
256
257         webpage = self._download_webpage(url, playlist_id)
258
259         # Only process container div with main playlist content skipping
260         # drop-down menu that uses similar pattern for videos (see
261         # https://github.com/rg3/youtube-dl/issues/11594).
262         container = self._search_regex(
263             r'(?s)(<div[^>]+class=["\']container.+)', webpage,
264             'container', default=webpage)
265
266         entries = self._extract_entries(container)
267
268         playlist = self._parse_json(
269             self._search_regex(
270                 r'playlistObject\s*=\s*({.+?});', webpage, 'playlist'),
271             playlist_id)
272
273         return self.playlist_result(
274             entries, playlist_id, playlist.get('title'), playlist.get('description'))
275
276
277 class PornHubPlaylistIE(PornHubPlaylistBaseIE):
278     _VALID_URL = r'https?://(?:www\.)?pornhub\.com/playlist/(?P<id>\d+)'
279     _TESTS = [{
280         'url': 'http://www.pornhub.com/playlist/4667351',
281         'info_dict': {
282             'id': '4667351',
283             'title': 'Nataly Hot',
284         },
285         'playlist_mincount': 2,
286     }]
287
288
289 class PornHubUserVideosIE(PornHubPlaylistBaseIE):
290     _VALID_URL = r'https?://(?:www\.)?pornhub\.com/users/(?P<id>[^/]+)/videos'
291     _TESTS = [{
292         'url': 'http://www.pornhub.com/users/zoe_ph/videos/public',
293         'info_dict': {
294             'id': 'zoe_ph',
295         },
296         'playlist_mincount': 171,
297     }, {
298         'url': 'http://www.pornhub.com/users/rushandlia/videos',
299         'only_matching': True,
300     }]
301
302     def _real_extract(self, url):
303         user_id = self._match_id(url)
304
305         entries = []
306         for page_num in itertools.count(1):
307             try:
308                 webpage = self._download_webpage(
309                     url, user_id, 'Downloading page %d' % page_num,
310                     query={'page': page_num})
311             except ExtractorError as e:
312                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
313                     break
314             page_entries = self._extract_entries(webpage)
315             if not page_entries:
316                 break
317             entries.extend(page_entries)
318
319         return self.playlist_result(entries, user_id)