[xhamsterembed] Fix extraction (closes #14308)
[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     dict_get,
10     ExtractorError,
11     int_or_none,
12     parse_duration,
13     unified_strdate,
14 )
15
16
17 class XHamsterIE(InfoExtractor):
18     _VALID_URL = r'''(?x)
19                     https?://
20                         (?:.+?\.)?xhamster\.com/
21                         (?:
22                             movies/(?P<id>\d+)/(?P<display_id>[^/]*)\.html|
23                             videos/(?P<display_id_2>[^/]*)-(?P<id_2>\d+)
24                         )
25                     '''
26
27     _TESTS = [{
28         'url': 'http://xhamster.com/movies/1509445/femaleagent_shy_beauty_takes_the_bait.html',
29         'md5': '8281348b8d3c53d39fffb377d24eac4e',
30         'info_dict': {
31             'id': '1509445',
32             'display_id': 'femaleagent_shy_beauty_takes_the_bait',
33             'ext': 'mp4',
34             'title': 'FemaleAgent Shy beauty takes the bait',
35             'upload_date': '20121014',
36             'uploader': 'Ruseful2011',
37             'duration': 893,
38             'age_limit': 18,
39             'categories': ['Fake Hub', 'Amateur', 'MILFs', 'POV', 'Boss', 'Office', 'Oral', 'Reality', 'Sexy'],
40         },
41     }, {
42         'url': 'http://xhamster.com/movies/2221348/britney_spears_sexy_booty.html?hd',
43         'info_dict': {
44             'id': '2221348',
45             'display_id': 'britney_spears_sexy_booty',
46             'ext': 'mp4',
47             'title': 'Britney Spears  Sexy Booty',
48             'upload_date': '20130914',
49             'uploader': 'jojo747400',
50             'duration': 200,
51             'age_limit': 18,
52             'categories': ['Britney Spears', 'Celebrities', 'HD Videos', 'Sexy', 'Sexy Booty'],
53         },
54         'params': {
55             'skip_download': True,
56         },
57     }, {
58         # empty seo
59         'url': 'http://xhamster.com/movies/5667973/.html',
60         'info_dict': {
61             'id': '5667973',
62             'ext': 'mp4',
63             'title': '....',
64             'upload_date': '20160208',
65             'uploader': 'parejafree',
66             'duration': 72,
67             'age_limit': 18,
68             'categories': ['Amateur', 'Blowjobs'],
69         },
70         'params': {
71             'skip_download': True,
72         },
73     }, {
74         'url': 'https://xhamster.com/movies/2272726/amber_slayed_by_the_knight.html',
75         'only_matching': True,
76     }, {
77         # This video is visible for marcoalfa123456's friends only
78         'url': 'https://it.xhamster.com/movies/7263980/la_mia_vicina.html',
79         'only_matching': True,
80     }, {
81         # new URL schema
82         'url': 'https://pt.xhamster.com/videos/euro-pedal-pumping-7937821',
83         'only_matching': True,
84     }]
85
86     def _real_extract(self, url):
87         mobj = re.match(self._VALID_URL, url)
88         video_id = mobj.group('id') or mobj.group('id_2')
89         display_id = mobj.group('display_id') or mobj.group('display_id_2')
90
91         webpage = self._download_webpage(url, video_id)
92
93         error = self._html_search_regex(
94             r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
95             webpage, 'error', default=None)
96         if error:
97             raise ExtractorError(error, expected=True)
98
99         title = self._html_search_regex(
100             [r'<h1[^>]*>([^<]+)</h1>',
101              r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
102              r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
103             webpage, 'title')
104
105         formats = []
106         format_urls = set()
107
108         sources = self._parse_json(
109             self._search_regex(
110                 r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
111                 default='{}'),
112             video_id, fatal=False)
113         for format_id, format_url in sources.items():
114             if not isinstance(format_url, compat_str):
115                 continue
116             if format_url in format_urls:
117                 continue
118             format_urls.add(format_url)
119             formats.append({
120                 'format_id': format_id,
121                 'url': format_url,
122                 'height': int_or_none(self._search_regex(
123                     r'^(\d+)[pP]', format_id, 'height', default=None))
124             })
125
126         video_url = self._search_regex(
127             [r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
128              r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
129              r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
130             webpage, 'video url', group='mp4', default=None)
131         if video_url and video_url not in format_urls:
132             formats.append({
133                 'url': video_url,
134             })
135
136         self._sort_formats(formats)
137
138         # Only a few videos have an description
139         mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
140         description = mobj.group(1) if mobj else None
141
142         upload_date = unified_strdate(self._search_regex(
143             r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
144             webpage, 'upload date', fatal=False))
145
146         uploader = self._html_search_regex(
147             r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
148             webpage, 'uploader', default='anonymous')
149
150         thumbnail = self._search_regex(
151             [r'''thumb\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
152              r'''<video[^>]+poster=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
153             webpage, 'thumbnail', fatal=False, group='thumbnail')
154
155         duration = parse_duration(self._search_regex(
156             [r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
157              r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
158             'duration', fatal=False))
159
160         view_count = int_or_none(self._search_regex(
161             r'content=["\']User(?:View|Play)s:(\d+)',
162             webpage, 'view count', fatal=False))
163
164         mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
165         (like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
166
167         mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
168         comment_count = mobj.group('commentcount') if mobj else 0
169
170         age_limit = self._rta_search(webpage)
171
172         categories_html = self._search_regex(
173             r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
174             'categories', default=None)
175         categories = [clean_html(category) for category in re.findall(
176             r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
177
178         return {
179             'id': video_id,
180             'display_id': display_id,
181             'title': title,
182             'description': description,
183             'upload_date': upload_date,
184             'uploader': uploader,
185             'thumbnail': thumbnail,
186             'duration': duration,
187             'view_count': view_count,
188             'like_count': int_or_none(like_count),
189             'dislike_count': int_or_none(dislike_count),
190             'comment_count': int_or_none(comment_count),
191             'age_limit': age_limit,
192             'categories': categories,
193             'formats': formats,
194         }
195
196
197 class XHamsterEmbedIE(InfoExtractor):
198     _VALID_URL = r'https?://(?:www\.)?xhamster\.com/xembed\.php\?video=(?P<id>\d+)'
199     _TEST = {
200         'url': 'http://xhamster.com/xembed.php?video=3328539',
201         'info_dict': {
202             'id': '3328539',
203             'ext': 'mp4',
204             'title': 'Pen Masturbation',
205             'upload_date': '20140728',
206             'uploader_id': 'anonymous',
207             'duration': 5,
208             'age_limit': 18,
209         }
210     }
211
212     @staticmethod
213     def _extract_urls(webpage):
214         return [url for _, url in re.findall(
215             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1',
216             webpage)]
217
218     def _real_extract(self, url):
219         video_id = self._match_id(url)
220
221         webpage = self._download_webpage(url, video_id)
222
223         video_url = self._search_regex(
224             r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
225             webpage, 'xhamster url', default=None)
226
227         if not video_url:
228             vars = self._parse_json(
229                 self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
230                 video_id)
231             video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
232
233         return self.url_result(video_url, 'XHamster')