[pornhub] Fix typo (Closes #9008)
[youtube-dl] / youtube_dl / extractor / pornhub.py
1 from __future__ import unicode_literals
2
3 import itertools
4 import os
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_HTTPError,
10     compat_urllib_parse_unquote,
11     compat_urllib_parse_unquote_plus,
12     compat_urllib_parse_urlparse,
13 )
14 from ..utils import (
15     ExtractorError,
16     int_or_none,
17     orderedSet,
18     sanitized_Request,
19     str_to_int,
20 )
21 from ..aes import (
22     aes_decrypt_text
23 )
24
25
26 class PornHubIE(InfoExtractor):
27     _VALID_URL = r'https?://(?:[a-z]+\.)?pornhub\.com/(?:view_video\.php\?viewkey=|embed/)(?P<id>[0-9a-z]+)'
28     _TESTS = [{
29         'url': 'http://www.pornhub.com/view_video.php?viewkey=648719015',
30         'md5': '1e19b41231a02eba417839222ac9d58e',
31         'info_dict': {
32             'id': '648719015',
33             'ext': 'mp4',
34             'title': 'Seductive Indian beauty strips down and fingers her pink pussy',
35             'uploader': 'Babes',
36             'duration': 361,
37             'view_count': int,
38             'like_count': int,
39             'dislike_count': int,
40             'comment_count': int,
41             'age_limit': 18,
42         }
43     }, {
44         'url': 'http://www.pornhub.com/view_video.php?viewkey=ph557bbb6676d2d',
45         'only_matching': True,
46     }, {
47         'url': 'http://fr.pornhub.com/view_video.php?viewkey=ph55ca2f9760862',
48         'only_matching': True,
49     }]
50
51     @classmethod
52     def _extract_url(cls, webpage):
53         mobj = re.search(
54             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?pornhub\.com/embed/\d+)\1', webpage)
55         if mobj:
56             return mobj.group('url')
57
58     def _extract_count(self, pattern, webpage, name):
59         return str_to_int(self._search_regex(
60             pattern, webpage, '%s count' % name, fatal=False))
61
62     def _real_extract(self, url):
63         video_id = self._match_id(url)
64
65         req = sanitized_Request(
66             'http://www.pornhub.com/view_video.php?viewkey=%s' % video_id)
67         req.add_header('Cookie', 'age_verified=1')
68         webpage = self._download_webpage(req, video_id)
69
70         error_msg = self._html_search_regex(
71             r'(?s)<div class="userMessageSection[^"]*".*?>(.*?)</div>',
72             webpage, 'error message', default=None)
73         if error_msg:
74             error_msg = re.sub(r'\s+', ' ', error_msg)
75             raise ExtractorError(
76                 'PornHub said: %s' % error_msg,
77                 expected=True, video_id=video_id)
78
79         flashvars = self._parse_json(
80             self._search_regex(
81                 r'var\s+flashvars_\d+\s*=\s*({.+?});', webpage, 'flashvars', default='{}'),
82             video_id)
83         if flashvars:
84             video_title = flashvars.get('video_title')
85             thumbnail = flashvars.get('image_url')
86             duration = int_or_none(flashvars.get('video_duration'))
87         else:
88             video_title, thumbnail, duration = [None] * 3
89
90         if not video_title:
91             video_title = self._html_search_regex(r'<h1 [^>]+>([^<]+)', webpage, 'title')
92
93         video_uploader = self._html_search_regex(
94             r'(?s)From:&nbsp;.+?<(?:a href="/users/|a href="/channels/|span class="username)[^>]+>(.+?)<',
95             webpage, 'uploader', fatal=False)
96
97         view_count = self._extract_count(
98             r'<span class="count">([\d,\.]+)</span> views', webpage, 'view')
99         like_count = self._extract_count(
100             r'<span class="votesUp">([\d,\.]+)</span>', webpage, 'like')
101         dislike_count = self._extract_count(
102             r'<span class="votesDown">([\d,\.]+)</span>', webpage, 'dislike')
103         comment_count = self._extract_count(
104             r'All Comments\s*<span>\(([\d,.]+)\)', webpage, 'comment')
105
106         video_urls = list(map(compat_urllib_parse_unquote, re.findall(r"player_quality_[0-9]{3}p\s*=\s*'([^']+)'", webpage)))
107         if webpage.find('"encrypted":true') != -1:
108             password = compat_urllib_parse_unquote_plus(
109                 self._search_regex(r'"video_title":"([^"]+)', webpage, 'password'))
110             video_urls = list(map(lambda s: aes_decrypt_text(s, password, 32).decode('utf-8'), video_urls))
111
112         formats = []
113         for video_url in video_urls:
114             path = compat_urllib_parse_urlparse(video_url).path
115             extension = os.path.splitext(path)[1][1:]
116             format = path.split('/')[5].split('_')[:2]
117             format = '-'.join(format)
118
119             m = re.match(r'^(?P<height>[0-9]+)[pP]-(?P<tbr>[0-9]+)[kK]$', format)
120             if m is None:
121                 height = None
122                 tbr = None
123             else:
124                 height = int(m.group('height'))
125                 tbr = int(m.group('tbr'))
126
127             formats.append({
128                 'url': video_url,
129                 'ext': extension,
130                 'format': format,
131                 'format_id': format,
132                 'tbr': tbr,
133                 'height': height,
134             })
135         self._sort_formats(formats)
136
137         return {
138             'id': video_id,
139             'uploader': video_uploader,
140             'title': video_title,
141             'thumbnail': thumbnail,
142             'duration': duration,
143             'view_count': view_count,
144             'like_count': like_count,
145             'dislike_count': dislike_count,
146             'comment_count': comment_count,
147             'formats': formats,
148             'age_limit': 18,
149         }
150
151
152 class PornHubPlaylistBaseIE(InfoExtractor):
153     def _extract_entries(self, webpage):
154         return [
155             self.url_result(
156                 'http://www.pornhub.com/%s' % video_url,
157                 PornHubIE.ie_key(), video_title=title)
158             for video_url, title in orderedSet(re.findall(
159                 r'href="/?(view_video\.php\?.*\bviewkey=[\da-z]+[^"]*)"[^>]*\s+title="([^"]+)"',
160                 webpage))
161         ]
162
163     def _real_extract(self, url):
164         playlist_id = self._match_id(url)
165
166         webpage = self._download_webpage(url, playlist_id)
167
168         entries = self._extract_entries(webpage)
169
170         playlist = self._parse_json(
171             self._search_regex(
172                 r'playlistObject\s*=\s*({.+?});', webpage, 'playlist'),
173             playlist_id)
174
175         return self.playlist_result(
176             entries, playlist_id, playlist.get('title'), playlist.get('description'))
177
178
179 class PornHubPlaylistIE(PornHubPlaylistBaseIE):
180     _VALID_URL = r'https?://(?:www\.)?pornhub\.com/playlist/(?P<id>\d+)'
181     _TESTS = [{
182         'url': 'http://www.pornhub.com/playlist/6201671',
183         'info_dict': {
184             'id': '6201671',
185             'title': 'P0p4',
186         },
187         'playlist_mincount': 35,
188     }]
189
190
191 class PornHubUserVideosIE(PornHubPlaylistBaseIE):
192     _VALID_URL = r'https?://(?:www\.)?pornhub\.com/users/(?P<id>[^/]+)/videos'
193     _TESTS = [{
194         'url': 'http://www.pornhub.com/users/zoe_ph/videos/public',
195         'info_dict': {
196             'id': 'zoe_ph',
197         },
198         'playlist_mincount': 171,
199     }, {
200         'url': 'http://www.pornhub.com/users/rushandlia/videos',
201         'only_matching': True,
202     }]
203
204     def _real_extract(self, url):
205         user_id = self._match_id(url)
206
207         entries = []
208         for page_num in itertools.count(1):
209             try:
210                 webpage = self._download_webpage(
211                     url, user_id, 'Downloading page %d' % page_num,
212                     query={'page': page_num})
213             except ExtractorError as e:
214                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
215                     break
216             page_entries = self._extract_entries(webpage)
217             if not page_entries:
218                 break
219             entries.extend(page_entries)
220
221         return self.playlist_result(entries, user_id)