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