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