[xhamster] Add support for xhamster.one (closes #20508)
[youtube-dl] / youtube_dl / extractor / xhamster.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import compat_str
7 from ..utils import (
8     clean_html,
9     determine_ext,
10     dict_get,
11     ExtractorError,
12     int_or_none,
13     parse_duration,
14     try_get,
15     unified_strdate,
16     url_or_none,
17 )
18
19
20 class XHamsterIE(InfoExtractor):
21     _VALID_URL = r'''(?x)
22                     https?://
23                         (?:.+?\.)?xhamster\.(?:com|one)/
24                         (?:
25                             movies/(?P<id>\d+)/(?P<display_id>[^/]*)\.html|
26                             videos/(?P<display_id_2>[^/]*)-(?P<id_2>\d+)
27                         )
28                     '''
29
30     _TESTS = [{
31         'url': 'http://xhamster.com/movies/1509445/femaleagent_shy_beauty_takes_the_bait.html',
32         'md5': '8281348b8d3c53d39fffb377d24eac4e',
33         'info_dict': {
34             'id': '1509445',
35             'display_id': 'femaleagent_shy_beauty_takes_the_bait',
36             'ext': 'mp4',
37             'title': 'FemaleAgent Shy beauty takes the bait',
38             'timestamp': 1350194821,
39             'upload_date': '20121014',
40             'uploader': 'Ruseful2011',
41             'duration': 893,
42             'age_limit': 18,
43             'categories': ['Fake Hub', 'Amateur', 'MILFs', 'POV', 'Beauti', 'Beauties', 'Beautiful', 'Boss', 'Office', 'Oral', 'Reality', 'Sexy', 'Taking'],
44         },
45     }, {
46         'url': 'http://xhamster.com/movies/2221348/britney_spears_sexy_booty.html?hd',
47         'info_dict': {
48             'id': '2221348',
49             'display_id': 'britney_spears_sexy_booty',
50             'ext': 'mp4',
51             'title': 'Britney Spears  Sexy Booty',
52             'timestamp': 1379123460,
53             'upload_date': '20130914',
54             'uploader': 'jojo747400',
55             'duration': 200,
56             'age_limit': 18,
57             'categories': ['Britney Spears', 'Celebrities', 'HD Videos', 'Sexy', 'Sexy Booty'],
58         },
59         'params': {
60             'skip_download': True,
61         },
62     }, {
63         # empty seo
64         'url': 'http://xhamster.com/movies/5667973/.html',
65         'info_dict': {
66             'id': '5667973',
67             'ext': 'mp4',
68             'title': '....',
69             'timestamp': 1454948101,
70             'upload_date': '20160208',
71             'uploader': 'parejafree',
72             'duration': 72,
73             'age_limit': 18,
74             'categories': ['Amateur', 'Blowjobs'],
75         },
76         'params': {
77             'skip_download': True,
78         },
79     }, {
80         # mobile site
81         'url': 'https://m.xhamster.com/videos/cute-teen-jacqueline-solo-masturbation-8559111',
82         'only_matching': True,
83     }, {
84         'url': 'https://xhamster.com/movies/2272726/amber_slayed_by_the_knight.html',
85         'only_matching': True,
86     }, {
87         # This video is visible for marcoalfa123456's friends only
88         'url': 'https://it.xhamster.com/movies/7263980/la_mia_vicina.html',
89         'only_matching': True,
90     }, {
91         # new URL schema
92         'url': 'https://pt.xhamster.com/videos/euro-pedal-pumping-7937821',
93         'only_matching': True,
94     }, {
95         'url': 'https://xhamster.one/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
96         'only_matching': True,
97     }]
98
99     def _real_extract(self, url):
100         mobj = re.match(self._VALID_URL, url)
101         video_id = mobj.group('id') or mobj.group('id_2')
102         display_id = mobj.group('display_id') or mobj.group('display_id_2')
103
104         desktop_url = re.sub(r'^(https?://(?:.+?\.)?)m\.', r'\1', url)
105         webpage = self._download_webpage(desktop_url, video_id)
106
107         error = self._html_search_regex(
108             r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
109             webpage, 'error', default=None)
110         if error:
111             raise ExtractorError(error, expected=True)
112
113         age_limit = self._rta_search(webpage)
114
115         def get_height(s):
116             return int_or_none(self._search_regex(
117                 r'^(\d+)[pP]', s, 'height', default=None))
118
119         initials = self._parse_json(
120             self._search_regex(
121                 r'window\.initials\s*=\s*({.+?})\s*;\s*\n', webpage, 'initials',
122                 default='{}'),
123             video_id, fatal=False)
124         if initials:
125             video = initials['videoModel']
126             title = video['title']
127             formats = []
128             for format_id, formats_dict in video['sources'].items():
129                 if not isinstance(formats_dict, dict):
130                     continue
131                 for quality, format_item in formats_dict.items():
132                     if format_id == 'download':
133                         # Download link takes some time to be generated,
134                         # skipping for now
135                         continue
136                         if not isinstance(format_item, dict):
137                             continue
138                         format_url = format_item.get('link')
139                         filesize = int_or_none(
140                             format_item.get('size'), invscale=1000000)
141                     else:
142                         format_url = format_item
143                         filesize = None
144                     format_url = url_or_none(format_url)
145                     if not format_url:
146                         continue
147                     formats.append({
148                         'format_id': '%s-%s' % (format_id, quality),
149                         'url': format_url,
150                         'ext': determine_ext(format_url, 'mp4'),
151                         'height': get_height(quality),
152                         'filesize': filesize,
153                     })
154             self._sort_formats(formats)
155
156             categories_list = video.get('categories')
157             if isinstance(categories_list, list):
158                 categories = []
159                 for c in categories_list:
160                     if not isinstance(c, dict):
161                         continue
162                     c_name = c.get('name')
163                     if isinstance(c_name, compat_str):
164                         categories.append(c_name)
165             else:
166                 categories = None
167
168             return {
169                 'id': video_id,
170                 'display_id': display_id,
171                 'title': title,
172                 'description': video.get('description'),
173                 'timestamp': int_or_none(video.get('created')),
174                 'uploader': try_get(
175                     video, lambda x: x['author']['name'], compat_str),
176                 'thumbnail': video.get('thumbURL'),
177                 'duration': int_or_none(video.get('duration')),
178                 'view_count': int_or_none(video.get('views')),
179                 'like_count': int_or_none(try_get(
180                     video, lambda x: x['rating']['likes'], int)),
181                 'dislike_count': int_or_none(try_get(
182                     video, lambda x: x['rating']['dislikes'], int)),
183                 'comment_count': int_or_none(video.get('views')),
184                 'age_limit': age_limit,
185                 'categories': categories,
186                 'formats': formats,
187             }
188
189         # Old layout fallback
190
191         title = self._html_search_regex(
192             [r'<h1[^>]*>([^<]+)</h1>',
193              r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
194              r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
195             webpage, 'title')
196
197         formats = []
198         format_urls = set()
199
200         sources = self._parse_json(
201             self._search_regex(
202                 r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
203                 default='{}'),
204             video_id, fatal=False)
205         for format_id, format_url in sources.items():
206             format_url = url_or_none(format_url)
207             if not format_url:
208                 continue
209             if format_url in format_urls:
210                 continue
211             format_urls.add(format_url)
212             formats.append({
213                 'format_id': format_id,
214                 'url': format_url,
215                 'height': get_height(format_id),
216             })
217
218         video_url = self._search_regex(
219             [r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
220              r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
221              r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
222             webpage, 'video url', group='mp4', default=None)
223         if video_url and video_url not in format_urls:
224             formats.append({
225                 'url': video_url,
226             })
227
228         self._sort_formats(formats)
229
230         # Only a few videos have an description
231         mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
232         description = mobj.group(1) if mobj else None
233
234         upload_date = unified_strdate(self._search_regex(
235             r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
236             webpage, 'upload date', fatal=False))
237
238         uploader = self._html_search_regex(
239             r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
240             webpage, 'uploader', default='anonymous')
241
242         thumbnail = self._search_regex(
243             [r'''["']thumbUrl["']\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
244              r'''<video[^>]+"poster"=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
245             webpage, 'thumbnail', fatal=False, group='thumbnail')
246
247         duration = parse_duration(self._search_regex(
248             [r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
249              r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
250             'duration', fatal=False))
251
252         view_count = int_or_none(self._search_regex(
253             r'content=["\']User(?:View|Play)s:(\d+)',
254             webpage, 'view count', fatal=False))
255
256         mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
257         (like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
258
259         mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
260         comment_count = mobj.group('commentcount') if mobj else 0
261
262         categories_html = self._search_regex(
263             r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
264             'categories', default=None)
265         categories = [clean_html(category) for category in re.findall(
266             r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
267
268         return {
269             'id': video_id,
270             'display_id': display_id,
271             'title': title,
272             'description': description,
273             'upload_date': upload_date,
274             'uploader': uploader,
275             'thumbnail': thumbnail,
276             'duration': duration,
277             'view_count': view_count,
278             'like_count': int_or_none(like_count),
279             'dislike_count': int_or_none(dislike_count),
280             'comment_count': int_or_none(comment_count),
281             'age_limit': age_limit,
282             'categories': categories,
283             'formats': formats,
284         }
285
286
287 class XHamsterEmbedIE(InfoExtractor):
288     _VALID_URL = r'https?://(?:.+?\.)?xhamster\.com/xembed\.php\?video=(?P<id>\d+)'
289     _TEST = {
290         'url': 'http://xhamster.com/xembed.php?video=3328539',
291         'info_dict': {
292             'id': '3328539',
293             'ext': 'mp4',
294             'title': 'Pen Masturbation',
295             'timestamp': 1406581861,
296             'upload_date': '20140728',
297             'uploader': 'ManyakisArt',
298             'duration': 5,
299             'age_limit': 18,
300         }
301     }
302
303     @staticmethod
304     def _extract_urls(webpage):
305         return [url for _, url in re.findall(
306             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1',
307             webpage)]
308
309     def _real_extract(self, url):
310         video_id = self._match_id(url)
311
312         webpage = self._download_webpage(url, video_id)
313
314         video_url = self._search_regex(
315             r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
316             webpage, 'xhamster url', default=None)
317
318         if not video_url:
319             vars = self._parse_json(
320                 self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
321                 video_id)
322             video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
323
324         return self.url_result(video_url, 'XHamster')