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