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