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