]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/xhamster.py
[NHK] Use new API URL
[youtube-dl.git] / youtube_dl / extractor / xhamster.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import compat_str
9 from ..utils import (
10     clean_html,
11     determine_ext,
12     dict_get,
13     extract_attributes,
14     ExtractorError,
15     float_or_none,
16     int_or_none,
17     parse_duration,
18     str_or_none,
19     try_get,
20     unified_strdate,
21     url_or_none,
22     urljoin,
23 )
24
25
26 class XHamsterIE(InfoExtractor):
27     _DOMAINS = r'(?:xhamster\.(?:com|one|desi)|xhms\.pro|xhamster\d+\.com|xhday\.com)'
28     _VALID_URL = r'''(?x)
29                     https?://
30                         (?:.+?\.)?%s/
31                         (?:
32                             movies/(?P<id>[\dA-Za-z]+)/(?P<display_id>[^/]*)\.html|
33                             videos/(?P<display_id_2>[^/]*)-(?P<id_2>[\dA-Za-z]+)
34                         )
35                     ''' % _DOMAINS
36     _TESTS = [{
37         'url': 'https://xhamster.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
38         'md5': '34e1ab926db5dc2750fed9e1f34304bb',
39         'info_dict': {
40             'id': '1509445',
41             'display_id': 'femaleagent-shy-beauty-takes-the-bait',
42             'ext': 'mp4',
43             'title': 'FemaleAgent Shy beauty takes the bait',
44             'timestamp': 1350194821,
45             'upload_date': '20121014',
46             'uploader': 'Ruseful2011',
47             'uploader_id': 'ruseful2011',
48             'duration': 893,
49             'age_limit': 18,
50         },
51     }, {
52         'url': 'https://xhamster.com/videos/britney-spears-sexy-booty-2221348?hd=',
53         'info_dict': {
54             'id': '2221348',
55             'display_id': 'britney-spears-sexy-booty',
56             'ext': 'mp4',
57             'title': 'Britney Spears  Sexy Booty',
58             'timestamp': 1379123460,
59             'upload_date': '20130914',
60             'uploader': 'jojo747400',
61             'duration': 200,
62             'age_limit': 18,
63         },
64         'params': {
65             'skip_download': True,
66         },
67     }, {
68         # empty seo, unavailable via new URL schema
69         'url': 'http://xhamster.com/movies/5667973/.html',
70         'info_dict': {
71             'id': '5667973',
72             'ext': 'mp4',
73             'title': '....',
74             'timestamp': 1454948101,
75             'upload_date': '20160208',
76             'uploader': 'parejafree',
77             'uploader_id': 'parejafree',
78             'duration': 72,
79             'age_limit': 18,
80         },
81         'params': {
82             'skip_download': True,
83         },
84     }, {
85         # mobile site
86         'url': 'https://m.xhamster.com/videos/cute-teen-jacqueline-solo-masturbation-8559111',
87         'only_matching': True,
88     }, {
89         'url': 'https://xhamster.com/movies/2272726/amber_slayed_by_the_knight.html',
90         'only_matching': True,
91     }, {
92         # This video is visible for marcoalfa123456's friends only
93         'url': 'https://it.xhamster.com/movies/7263980/la_mia_vicina.html',
94         'only_matching': True,
95     }, {
96         # new URL schema
97         'url': 'https://pt.xhamster.com/videos/euro-pedal-pumping-7937821',
98         'only_matching': True,
99     }, {
100         'url': 'https://xhamster.one/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
101         'only_matching': True,
102     }, {
103         'url': 'https://xhamster.desi/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
104         'only_matching': True,
105     }, {
106         'url': 'https://xhamster2.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
107         'only_matching': True,
108     }, {
109         'url': 'https://xhamster11.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
110         'only_matching': True,
111     }, {
112         'url': 'https://xhamster26.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
113         'only_matching': True,
114     }, {
115         'url': 'http://xhamster.com/movies/1509445/femaleagent_shy_beauty_takes_the_bait.html',
116         'only_matching': True,
117     }, {
118         'url': 'http://xhamster.com/movies/2221348/britney_spears_sexy_booty.html?hd',
119         'only_matching': True,
120     }, {
121         'url': 'http://de.xhamster.com/videos/skinny-girl-fucks-herself-hard-in-the-forest-xhnBJZx',
122         'only_matching': True,
123     }, {
124         'url': 'https://xhday.com/videos/strapless-threesome-xhh7yVf',
125         'only_matching': True,
126     }]
127
128     def _real_extract(self, url):
129         mobj = re.match(self._VALID_URL, url)
130         video_id = mobj.group('id') or mobj.group('id_2')
131         display_id = mobj.group('display_id') or mobj.group('display_id_2')
132
133         desktop_url = re.sub(r'^(https?://(?:.+?\.)?)m\.', r'\1', url)
134         webpage, urlh = self._download_webpage_handle(desktop_url, video_id)
135
136         error = self._html_search_regex(
137             r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
138             webpage, 'error', default=None)
139         if error:
140             raise ExtractorError(error, expected=True)
141
142         age_limit = self._rta_search(webpage)
143
144         def get_height(s):
145             return int_or_none(self._search_regex(
146                 r'^(\d+)[pP]', s, 'height', default=None))
147
148         initials = self._parse_json(
149             self._search_regex(
150                 (r'window\.initials\s*=\s*({.+?})\s*;\s*</script>',
151                  r'window\.initials\s*=\s*({.+?})\s*;'), webpage, 'initials',
152                 default='{}'),
153             video_id, fatal=False)
154         if initials:
155             video = initials['videoModel']
156             title = video['title']
157             formats = []
158             format_urls = set()
159             format_sizes = {}
160             sources = try_get(video, lambda x: x['sources'], dict) or {}
161             for format_id, formats_dict in sources.items():
162                 if not isinstance(formats_dict, dict):
163                     continue
164                 download_sources = try_get(sources, lambda x: x['download'], dict) or {}
165                 for quality, format_dict in download_sources.items():
166                     if not isinstance(format_dict, dict):
167                         continue
168                     format_sizes[quality] = float_or_none(format_dict.get('size'))
169                 for quality, format_item in formats_dict.items():
170                     if format_id == 'download':
171                         # Download link takes some time to be generated,
172                         # skipping for now
173                         continue
174                     format_url = format_item
175                     format_url = url_or_none(format_url)
176                     if not format_url or format_url in format_urls:
177                         continue
178                     format_urls.add(format_url)
179                     formats.append({
180                         'format_id': '%s-%s' % (format_id, quality),
181                         'url': format_url,
182                         'ext': determine_ext(format_url, 'mp4'),
183                         'height': get_height(quality),
184                         'filesize': format_sizes.get(quality),
185                         'http_headers': {
186                             'Referer': urlh.geturl(),
187                         },
188                     })
189             xplayer_sources = try_get(
190                 initials, lambda x: x['xplayerSettings']['sources'], dict)
191             if xplayer_sources:
192                 hls_sources = xplayer_sources.get('hls')
193                 if isinstance(hls_sources, dict):
194                     for hls_format_key in ('url', 'fallback'):
195                         hls_url = hls_sources.get(hls_format_key)
196                         if not hls_url:
197                             continue
198                         hls_url = urljoin(url, hls_url)
199                         if not hls_url or hls_url in format_urls:
200                             continue
201                         format_urls.add(hls_url)
202                         formats.extend(self._extract_m3u8_formats(
203                             hls_url, video_id, 'mp4', entry_protocol='m3u8_native',
204                             m3u8_id='hls', fatal=False))
205                 standard_sources = xplayer_sources.get('standard')
206                 if isinstance(standard_sources, dict):
207                     for format_id, formats_list in standard_sources.items():
208                         if not isinstance(formats_list, list):
209                             continue
210                         for standard_format in formats_list:
211                             if not isinstance(standard_format, dict):
212                                 continue
213                             for standard_format_key in ('url', 'fallback'):
214                                 standard_url = standard_format.get(standard_format_key)
215                                 if not standard_url:
216                                     continue
217                                 standard_url = urljoin(url, standard_url)
218                                 if not standard_url or standard_url in format_urls:
219                                     continue
220                                 format_urls.add(standard_url)
221                                 ext = determine_ext(standard_url, 'mp4')
222                                 if ext == 'm3u8':
223                                     formats.extend(self._extract_m3u8_formats(
224                                         standard_url, video_id, 'mp4', entry_protocol='m3u8_native',
225                                         m3u8_id='hls', fatal=False))
226                                     continue
227                                 quality = (str_or_none(standard_format.get('quality'))
228                                            or str_or_none(standard_format.get('label'))
229                                            or '')
230                                 formats.append({
231                                     'format_id': '%s-%s' % (format_id, quality),
232                                     'url': standard_url,
233                                     'ext': ext,
234                                     'height': get_height(quality),
235                                     'filesize': format_sizes.get(quality),
236                                     'http_headers': {
237                                         'Referer': standard_url,
238                                     },
239                                 })
240             self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
241
242             categories_list = video.get('categories')
243             if isinstance(categories_list, list):
244                 categories = []
245                 for c in categories_list:
246                     if not isinstance(c, dict):
247                         continue
248                     c_name = c.get('name')
249                     if isinstance(c_name, compat_str):
250                         categories.append(c_name)
251             else:
252                 categories = None
253
254             uploader_url = url_or_none(try_get(video, lambda x: x['author']['pageURL']))
255             return {
256                 'id': video_id,
257                 'display_id': display_id,
258                 'title': title,
259                 'description': video.get('description'),
260                 'timestamp': int_or_none(video.get('created')),
261                 'uploader': try_get(
262                     video, lambda x: x['author']['name'], compat_str),
263                 'uploader_url': uploader_url,
264                 'uploader_id': uploader_url.split('/')[-1] if uploader_url else None,
265                 'thumbnail': video.get('thumbURL'),
266                 'duration': int_or_none(video.get('duration')),
267                 'view_count': int_or_none(video.get('views')),
268                 'like_count': int_or_none(try_get(
269                     video, lambda x: x['rating']['likes'], int)),
270                 'dislike_count': int_or_none(try_get(
271                     video, lambda x: x['rating']['dislikes'], int)),
272                 'comment_count': int_or_none(video.get('views')),
273                 'age_limit': age_limit if age_limit is not None else 18,
274                 'categories': categories,
275                 'formats': formats,
276             }
277
278         # Old layout fallback
279
280         title = self._html_search_regex(
281             [r'<h1[^>]*>([^<]+)</h1>',
282              r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
283              r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
284             webpage, 'title')
285
286         formats = []
287         format_urls = set()
288
289         sources = self._parse_json(
290             self._search_regex(
291                 r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
292                 default='{}'),
293             video_id, fatal=False)
294         for format_id, format_url in sources.items():
295             format_url = url_or_none(format_url)
296             if not format_url:
297                 continue
298             if format_url in format_urls:
299                 continue
300             format_urls.add(format_url)
301             formats.append({
302                 'format_id': format_id,
303                 'url': format_url,
304                 'height': get_height(format_id),
305             })
306
307         video_url = self._search_regex(
308             [r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
309              r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
310              r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
311             webpage, 'video url', group='mp4', default=None)
312         if video_url and video_url not in format_urls:
313             formats.append({
314                 'url': video_url,
315             })
316
317         self._sort_formats(formats)
318
319         # Only a few videos have an description
320         mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
321         description = mobj.group(1) if mobj else None
322
323         upload_date = unified_strdate(self._search_regex(
324             r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
325             webpage, 'upload date', fatal=False))
326
327         uploader = self._html_search_regex(
328             r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
329             webpage, 'uploader', default='anonymous')
330
331         thumbnail = self._search_regex(
332             [r'''["']thumbUrl["']\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
333              r'''<video[^>]+"poster"=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
334             webpage, 'thumbnail', fatal=False, group='thumbnail')
335
336         duration = parse_duration(self._search_regex(
337             [r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
338              r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
339             'duration', fatal=False))
340
341         view_count = int_or_none(self._search_regex(
342             r'content=["\']User(?:View|Play)s:(\d+)',
343             webpage, 'view count', fatal=False))
344
345         mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
346         (like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
347
348         mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
349         comment_count = mobj.group('commentcount') if mobj else 0
350
351         categories_html = self._search_regex(
352             r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
353             'categories', default=None)
354         categories = [clean_html(category) for category in re.findall(
355             r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
356
357         return {
358             'id': video_id,
359             'display_id': display_id,
360             'title': title,
361             'description': description,
362             'upload_date': upload_date,
363             'uploader': uploader,
364             'uploader_id': uploader.lower() if uploader else None,
365             'thumbnail': thumbnail,
366             'duration': duration,
367             'view_count': view_count,
368             'like_count': int_or_none(like_count),
369             'dislike_count': int_or_none(dislike_count),
370             'comment_count': int_or_none(comment_count),
371             'age_limit': age_limit,
372             'categories': categories,
373             'formats': formats,
374         }
375
376
377 class XHamsterEmbedIE(InfoExtractor):
378     _VALID_URL = r'https?://(?:.+?\.)?%s/xembed\.php\?video=(?P<id>\d+)' % XHamsterIE._DOMAINS
379     _TEST = {
380         'url': 'http://xhamster.com/xembed.php?video=3328539',
381         'info_dict': {
382             'id': '3328539',
383             'ext': 'mp4',
384             'title': 'Pen Masturbation',
385             'timestamp': 1406581861,
386             'upload_date': '20140728',
387             'uploader': 'ManyakisArt',
388             'duration': 5,
389             'age_limit': 18,
390         }
391     }
392
393     @staticmethod
394     def _extract_urls(webpage):
395         return [url for _, url in re.findall(
396             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1',
397             webpage)]
398
399     def _real_extract(self, url):
400         video_id = self._match_id(url)
401
402         webpage = self._download_webpage(url, video_id)
403
404         video_url = self._search_regex(
405             r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
406             webpage, 'xhamster url', default=None)
407
408         if not video_url:
409             vars = self._parse_json(
410                 self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
411                 video_id)
412             video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
413
414         return self.url_result(video_url, 'XHamster')
415
416
417 class XHamsterUserIE(InfoExtractor):
418     _VALID_URL = r'https?://(?:.+?\.)?%s/users/(?P<id>[^/?#&]+)' % XHamsterIE._DOMAINS
419     _TESTS = [{
420         # Paginated user profile
421         'url': 'https://xhamster.com/users/netvideogirls/videos',
422         'info_dict': {
423             'id': 'netvideogirls',
424         },
425         'playlist_mincount': 267,
426     }, {
427         # Non-paginated user profile
428         'url': 'https://xhamster.com/users/firatkaan/videos',
429         'info_dict': {
430             'id': 'firatkaan',
431         },
432         'playlist_mincount': 1,
433     }, {
434         'url': 'https://xhday.com/users/mobhunter',
435         'only_matching': True,
436     }]
437
438     def _entries(self, user_id):
439         next_page_url = 'https://xhamster.com/users/%s/videos/1' % user_id
440         for pagenum in itertools.count(1):
441             page = self._download_webpage(
442                 next_page_url, user_id, 'Downloading page %s' % pagenum)
443             for video_tag in re.findall(
444                     r'(<a[^>]+class=["\'].*?\bvideo-thumb__image-container[^>]+>)',
445                     page):
446                 video = extract_attributes(video_tag)
447                 video_url = url_or_none(video.get('href'))
448                 if not video_url or not XHamsterIE.suitable(video_url):
449                     continue
450                 video_id = XHamsterIE._match_id(video_url)
451                 yield self.url_result(
452                     video_url, ie=XHamsterIE.ie_key(), video_id=video_id)
453             mobj = re.search(r'<a[^>]+data-page=["\']next[^>]+>', page)
454             if not mobj:
455                 break
456             next_page = extract_attributes(mobj.group(0))
457             next_page_url = url_or_none(next_page.get('href'))
458             if not next_page_url:
459                 break
460
461     def _real_extract(self, url):
462         user_id = self._match_id(url)
463         return self.playlist_result(self._entries(user_id), user_id)