[cleanup] Misc (#8968)
[yt-dlp.git] / yt_dlp / extractor / dailymotion.py
blobc570a4f52641df0d899a62d2e3979b57b5268f9f
1 import functools
2 import json
3 import re
4 import urllib.parse
6 from .common import InfoExtractor
7 from ..networking.exceptions import HTTPError
8 from ..utils import (
9 ExtractorError,
10 OnDemandPagedList,
11 age_restricted,
12 clean_html,
13 int_or_none,
14 traverse_obj,
15 try_get,
16 unescapeHTML,
17 unsmuggle_url,
18 urlencode_postdata,
22 class DailymotionBaseInfoExtractor(InfoExtractor):
23 _FAMILY_FILTER = None
24 _HEADERS = {
25 'Content-Type': 'application/json',
26 'Origin': 'https://www.dailymotion.com',
28 _NETRC_MACHINE = 'dailymotion'
30 def _get_dailymotion_cookies(self):
31 return self._get_cookies('https://www.dailymotion.com/')
33 @staticmethod
34 def _get_cookie_value(cookies, name):
35 cookie = cookies.get(name)
36 if cookie:
37 return cookie.value
39 def _set_dailymotion_cookie(self, name, value):
40 self._set_cookie('www.dailymotion.com', name, value)
42 def _real_initialize(self):
43 cookies = self._get_dailymotion_cookies()
44 ff = self._get_cookie_value(cookies, 'ff')
45 self._FAMILY_FILTER = ff == 'on' if ff else age_restricted(18, self.get_param('age_limit'))
46 self._set_dailymotion_cookie('ff', 'on' if self._FAMILY_FILTER else 'off')
48 def _get_token(self, xid):
49 cookies = self._get_dailymotion_cookies()
50 token = self._get_cookie_value(cookies, 'access_token') or self._get_cookie_value(cookies, 'client_token')
51 if token:
52 return token
54 data = {
55 'client_id': 'f1a362d288c1b98099c7',
56 'client_secret': 'eea605b96e01c796ff369935357eca920c5da4c5',
58 username, password = self._get_login_info()
59 if username:
60 data.update({
61 'grant_type': 'password',
62 'password': password,
63 'username': username,
65 else:
66 data['grant_type'] = 'client_credentials'
67 try:
68 token = self._download_json(
69 'https://graphql.api.dailymotion.com/oauth/token',
70 None, 'Downloading Access Token',
71 data=urlencode_postdata(data))['access_token']
72 except ExtractorError as e:
73 if isinstance(e.cause, HTTPError) and e.cause.status == 400:
74 raise ExtractorError(self._parse_json(
75 e.cause.response.read().decode(), xid)['error_description'], expected=True)
76 raise
77 self._set_dailymotion_cookie('access_token' if username else 'client_token', token)
78 return token
80 def _call_api(self, object_type, xid, object_fields, note, filter_extra=None):
81 if not self._HEADERS.get('Authorization'):
82 self._HEADERS['Authorization'] = f'Bearer {self._get_token(xid)}'
84 resp = self._download_json(
85 'https://graphql.api.dailymotion.com/', xid, note, data=json.dumps({
86 'query': '''{
87 %s(xid: "%s"%s) {
90 }''' % (object_type, xid, ', ' + filter_extra if filter_extra else '', object_fields),
91 }).encode(), headers=self._HEADERS)
92 obj = resp['data'][object_type]
93 if not obj:
94 raise ExtractorError(resp['errors'][0]['message'], expected=True)
95 return obj
98 class DailymotionIE(DailymotionBaseInfoExtractor):
99 _VALID_URL = r'''(?ix)
100 https?://
102 (?:(?:www|touch|geo)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:(?:embed|swf|\#)/)|player(?:/\w+)?\.html\?)?video|swf)|
103 (?:www\.)?lequipe\.fr/video
105 [/=](?P<id>[^/?_&]+)(?:.+?\bplaylist=(?P<playlist_id>x[0-9a-z]+))?
107 IE_NAME = 'dailymotion'
108 _EMBED_REGEX = [r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1']
109 _TESTS = [{
110 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
111 'md5': '074b95bdee76b9e3654137aee9c79dfe',
112 'info_dict': {
113 'id': 'x5kesuj',
114 'ext': 'mp4',
115 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
116 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
117 'duration': 187,
118 'timestamp': 1493651285,
119 'upload_date': '20170501',
120 'uploader': 'Deadline',
121 'uploader_id': 'x1xm8ri',
122 'age_limit': 0,
123 'view_count': int,
124 'like_count': int,
125 'tags': ['hollywood', 'celeb', 'celebrity', 'movies', 'red carpet'],
126 'thumbnail': r're:https://(?:s[12]\.)dmcdn\.net/v/K456B1aXqIx58LKWQ/x1080',
128 }, {
129 'url': 'https://geo.dailymotion.com/player.html?video=x89eyek&mute=true',
130 'md5': 'e2f9717c6604773f963f069ca53a07f8',
131 'info_dict': {
132 'id': 'x89eyek',
133 'ext': 'mp4',
134 'title': "En quête d'esprit du 27/03/2022",
135 'description': 'md5:66542b9f4df2eb23f314fc097488e553',
136 'duration': 2756,
137 'timestamp': 1648383669,
138 'upload_date': '20220327',
139 'uploader': 'CNEWS',
140 'uploader_id': 'x24vth',
141 'age_limit': 0,
142 'view_count': int,
143 'like_count': int,
144 'tags': ['en_quete_d_esprit'],
145 'thumbnail': r're:https://(?:s[12]\.)dmcdn\.net/v/Tncwi1YNg_RUl7ueu/x1080',
147 }, {
148 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
149 'md5': '2137c41a8e78554bb09225b8eb322406',
150 'info_dict': {
151 'id': 'x2iuewm',
152 'ext': 'mp4',
153 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
154 'description': 'Several come bundled with the Steam Controller.',
155 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
156 'duration': 74,
157 'timestamp': 1425657362,
158 'upload_date': '20150306',
159 'uploader': 'IGN',
160 'uploader_id': 'xijv66',
161 'age_limit': 0,
162 'view_count': int,
164 'skip': 'video gone',
165 }, {
166 # Vevo video
167 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
168 'info_dict': {
169 'title': 'Roar (Official)',
170 'id': 'USUV71301934',
171 'ext': 'mp4',
172 'uploader': 'Katy Perry',
173 'upload_date': '20130905',
175 'params': {
176 'skip_download': True,
178 'skip': 'VEVO is only available in some countries',
179 }, {
180 # age-restricted video
181 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
182 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
183 'info_dict': {
184 'id': 'xyh2zz',
185 'ext': 'mp4',
186 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
187 'uploader': 'HotWaves1012',
188 'age_limit': 18,
190 'skip': 'video gone',
191 }, {
192 # geo-restricted, player v5
193 'url': 'http://www.dailymotion.com/video/xhza0o',
194 'only_matching': True,
195 }, {
196 # with subtitles
197 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
198 'only_matching': True,
199 }, {
200 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
201 'only_matching': True,
202 }, {
203 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
204 'only_matching': True,
205 }, {
206 'url': 'https://www.lequipe.fr/video/x791mem',
207 'only_matching': True,
208 }, {
209 'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2',
210 'only_matching': True,
211 }, {
212 'url': 'https://www.dailymotion.com/video/x3z49k?playlist=xv4bw',
213 'only_matching': True,
214 }, {
215 'url': 'https://geo.dailymotion.com/player/x86gw.html?video=k46oCapRs4iikoz9DWy',
216 'only_matching': True,
217 }, {
218 'url': 'https://geo.dailymotion.com/player/xakln.html?video=x8mjju4&customConfig%5BcustomParams%5D=%2Ffr-fr%2Ftennis%2Fwimbledon-mens-singles%2Farticles-video',
219 'only_matching': True,
221 _GEO_BYPASS = False
222 _COMMON_MEDIA_FIELDS = '''description
223 geoblockedCountries {
224 allowed
226 xid'''
228 @classmethod
229 def _extract_embed_urls(cls, url, webpage):
230 # https://developer.dailymotion.com/player#player-parameters
231 yield from super()._extract_embed_urls(url, webpage)
232 for mobj in re.finditer(
233 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s*:\s*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage):
234 yield from 'https://www.dailymotion.com/embed/video/' + mobj.group('id')
236 def _real_extract(self, url):
237 url, smuggled_data = unsmuggle_url(url)
238 video_id, playlist_id = self._match_valid_url(url).groups()
240 if playlist_id:
241 if self._yes_playlist(playlist_id, video_id):
242 return self.url_result(
243 'http://www.dailymotion.com/playlist/' + playlist_id,
244 'DailymotionPlaylist', playlist_id)
246 password = self.get_param('videopassword')
247 media = self._call_api(
248 'media', video_id, '''... on Video {
250 stats {
251 likes {
252 total
254 views {
255 total
259 ... on Live {
261 audienceCount
262 isOnAir
263 }''' % (self._COMMON_MEDIA_FIELDS, self._COMMON_MEDIA_FIELDS), 'Downloading media JSON metadata',
264 'password: "%s"' % self.get_param('videopassword') if password else None)
265 xid = media['xid']
267 metadata = self._download_json(
268 'https://www.dailymotion.com/player/metadata/video/' + xid,
269 xid, 'Downloading metadata JSON',
270 query=traverse_obj(smuggled_data, 'query') or {'app': 'com.dailymotion.neon'})
272 error = metadata.get('error')
273 if error:
274 title = error.get('title') or error['raw_message']
275 # See https://developer.dailymotion.com/api#access-error
276 if error.get('code') == 'DM007':
277 allowed_countries = try_get(media, lambda x: x['geoblockedCountries']['allowed'], list)
278 self.raise_geo_restricted(msg=title, countries=allowed_countries)
279 raise ExtractorError(
280 '%s said: %s' % (self.IE_NAME, title), expected=True)
282 title = metadata['title']
283 is_live = media.get('isOnAir')
284 formats = []
285 for quality, media_list in metadata['qualities'].items():
286 for m in media_list:
287 media_url = m.get('url')
288 media_type = m.get('type')
289 if not media_url or media_type == 'application/vnd.lumberjack.manifest':
290 continue
291 if media_type == 'application/x-mpegURL':
292 formats.extend(self._extract_m3u8_formats(
293 media_url, video_id, 'mp4', live=is_live, m3u8_id='hls', fatal=False))
294 else:
295 f = {
296 'url': media_url,
297 'format_id': 'http-' + quality,
299 m = re.search(r'/H264-(\d+)x(\d+)(?:-(60)/)?', media_url)
300 if m:
301 width, height, fps = map(int_or_none, m.groups())
302 f.update({
303 'fps': fps,
304 'height': height,
305 'width': width,
307 formats.append(f)
308 for f in formats:
309 f['url'] = f['url'].split('#')[0]
310 if not f.get('fps') and f['format_id'].endswith('@60'):
311 f['fps'] = 60
313 subtitles = {}
314 subtitles_data = try_get(metadata, lambda x: x['subtitles']['data'], dict) or {}
315 for subtitle_lang, subtitle in subtitles_data.items():
316 subtitles[subtitle_lang] = [{
317 'url': subtitle_url,
318 } for subtitle_url in subtitle.get('urls', [])]
320 thumbnails = []
321 for height, poster_url in metadata.get('posters', {}).items():
322 thumbnails.append({
323 'height': int_or_none(height),
324 'id': height,
325 'url': poster_url,
328 owner = metadata.get('owner') or {}
329 stats = media.get('stats') or {}
330 get_count = lambda x: int_or_none(try_get(stats, lambda y: y[x + 's']['total']))
332 return {
333 'id': video_id,
334 'title': title,
335 'description': clean_html(media.get('description')),
336 'thumbnails': thumbnails,
337 'duration': int_or_none(metadata.get('duration')) or None,
338 'timestamp': int_or_none(metadata.get('created_time')),
339 'uploader': owner.get('screenname'),
340 'uploader_id': owner.get('id') or metadata.get('screenname'),
341 'age_limit': 18 if metadata.get('explicit') else 0,
342 'tags': metadata.get('tags'),
343 'view_count': get_count('view') or int_or_none(media.get('audienceCount')),
344 'like_count': get_count('like'),
345 'formats': formats,
346 'subtitles': subtitles,
347 'is_live': is_live,
351 class DailymotionPlaylistBaseIE(DailymotionBaseInfoExtractor):
352 _PAGE_SIZE = 100
354 def _fetch_page(self, playlist_id, page):
355 page += 1
356 videos = self._call_api(
357 self._OBJECT_TYPE, playlist_id,
358 '''videos(allowExplicit: %s, first: %d, page: %d) {
359 edges {
360 node {
365 }''' % ('false' if self._FAMILY_FILTER else 'true', self._PAGE_SIZE, page),
366 'Downloading page %d' % page)['videos']
367 for edge in videos['edges']:
368 node = edge['node']
369 yield self.url_result(
370 node['url'], DailymotionIE.ie_key(), node['xid'])
372 def _real_extract(self, url):
373 playlist_id = self._match_id(url)
374 entries = OnDemandPagedList(functools.partial(
375 self._fetch_page, playlist_id), self._PAGE_SIZE)
376 return self.playlist_result(
377 entries, playlist_id)
380 class DailymotionPlaylistIE(DailymotionPlaylistBaseIE):
381 IE_NAME = 'dailymotion:playlist'
382 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
383 _TESTS = [{
384 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
385 'info_dict': {
386 'id': 'xv4bw',
388 'playlist_mincount': 20,
390 _OBJECT_TYPE = 'collection'
392 @classmethod
393 def _extract_embed_urls(cls, url, webpage):
394 # Look for embedded Dailymotion playlist player (#3822)
395 for mobj in re.finditer(
396 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.[a-z]{2,3}/widget/jukebox\?.+?)\1',
397 webpage):
398 for p in re.findall(r'list\[\]=/playlist/([^/]+)/', unescapeHTML(mobj.group('url'))):
399 yield '//dailymotion.com/playlist/%s' % p
402 class DailymotionSearchIE(DailymotionPlaylistBaseIE):
403 IE_NAME = 'dailymotion:search'
404 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/search/(?P<id>[^/?#]+)/videos'
405 _PAGE_SIZE = 20
406 _TESTS = [{
407 'url': 'http://www.dailymotion.com/search/king of turtles/videos',
408 'info_dict': {
409 'id': 'king of turtles',
410 'title': 'king of turtles',
412 'playlist_mincount': 90,
414 _SEARCH_QUERY = 'query SEARCH_QUERY( $query: String! $page: Int $limit: Int ) { search { videos( query: $query first: $limit page: $page ) { edges { node { xid } } } } } '
416 def _call_search_api(self, term, page, note):
417 if not self._HEADERS.get('Authorization'):
418 self._HEADERS['Authorization'] = f'Bearer {self._get_token(term)}'
419 resp = self._download_json(
420 'https://graphql.api.dailymotion.com/', None, note, data=json.dumps({
421 'operationName': 'SEARCH_QUERY',
422 'query': self._SEARCH_QUERY,
423 'variables': {
424 'limit': 20,
425 'page': page,
426 'query': term,
428 }).encode(), headers=self._HEADERS)
429 obj = traverse_obj(resp, ('data', 'search', {dict}))
430 if not obj:
431 raise ExtractorError(
432 traverse_obj(resp, ('errors', 0, 'message', {str})) or 'Could not fetch search data')
434 return obj
436 def _fetch_page(self, term, page):
437 page += 1
438 response = self._call_search_api(term, page, f'Searching "{term}" page {page}')
439 for xid in traverse_obj(response, ('videos', 'edges', ..., 'node', 'xid')):
440 yield self.url_result(f'https://www.dailymotion.com/video/{xid}', DailymotionIE, xid)
442 def _real_extract(self, url):
443 term = urllib.parse.unquote_plus(self._match_id(url))
444 return self.playlist_result(
445 OnDemandPagedList(functools.partial(self._fetch_page, term), self._PAGE_SIZE), term, term)
448 class DailymotionUserIE(DailymotionPlaylistBaseIE):
449 IE_NAME = 'dailymotion:user'
450 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist|search)/)(?:(?:old/)?user/)?(?P<id>[^/?#]+)'
451 _TESTS = [{
452 'url': 'https://www.dailymotion.com/user/nqtv',
453 'info_dict': {
454 'id': 'nqtv',
456 'playlist_mincount': 152,
457 }, {
458 'url': 'http://www.dailymotion.com/user/UnderProject',
459 'info_dict': {
460 'id': 'UnderProject',
462 'playlist_mincount': 1000,
463 'skip': 'Takes too long time',
464 }, {
465 'url': 'https://www.dailymotion.com/user/nqtv',
466 'info_dict': {
467 'id': 'nqtv',
469 'playlist_mincount': 148,
470 'params': {
471 'age_limit': 0,
474 _OBJECT_TYPE = 'channel'