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