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