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