]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/dailymotion.py
745971900b23f1cbf44ce286b9c4a4a7e527a3da
[youtubedl] / youtube_dl / extractor / dailymotion.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import functools
6 import hashlib
7 import itertools
8 import json
9 import random
10 import re
11 import string
12
13 from .common import InfoExtractor
14 from ..compat import compat_struct_pack
15 from ..utils import (
16 determine_ext,
17 error_to_compat_str,
18 ExtractorError,
19 int_or_none,
20 mimetype2ext,
21 OnDemandPagedList,
22 parse_iso8601,
23 sanitized_Request,
24 str_to_int,
25 try_get,
26 unescapeHTML,
27 update_url_query,
28 url_or_none,
29 urlencode_postdata,
30 )
31
32
33 class DailymotionBaseInfoExtractor(InfoExtractor):
34 @staticmethod
35 def _build_request(url):
36 """Build a request with the family filter disabled"""
37 request = sanitized_Request(url)
38 request.add_header('Cookie', 'family_filter=off; ff=off')
39 return request
40
41 def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
42 request = self._build_request(url)
43 return self._download_webpage_handle(request, *args, **kwargs)
44
45 def _download_webpage_no_ff(self, url, *args, **kwargs):
46 request = self._build_request(url)
47 return self._download_webpage(request, *args, **kwargs)
48
49
50 class DailymotionIE(DailymotionBaseInfoExtractor):
51 _VALID_URL = r'''(?ix)
52 https?://
53 (?:
54 (?:(?:www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|\#)/)?video|swf)|
55 (?:www\.)?lequipe\.fr/video
56 )
57 /(?P<id>[^/?_]+)
58 '''
59 IE_NAME = 'dailymotion'
60
61 _FORMATS = [
62 ('stream_h264_ld_url', 'ld'),
63 ('stream_h264_url', 'standard'),
64 ('stream_h264_hq_url', 'hq'),
65 ('stream_h264_hd_url', 'hd'),
66 ('stream_h264_hd1080_url', 'hd180'),
67 ]
68
69 _TESTS = [{
70 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
71 'md5': '074b95bdee76b9e3654137aee9c79dfe',
72 'info_dict': {
73 'id': 'x5kesuj',
74 'ext': 'mp4',
75 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
76 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
77 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
78 'duration': 187,
79 'timestamp': 1493651285,
80 'upload_date': '20170501',
81 'uploader': 'Deadline',
82 'uploader_id': 'x1xm8ri',
83 'age_limit': 0,
84 },
85 }, {
86 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
87 'md5': '2137c41a8e78554bb09225b8eb322406',
88 'info_dict': {
89 'id': 'x2iuewm',
90 'ext': 'mp4',
91 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
92 'description': 'Several come bundled with the Steam Controller.',
93 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
94 'duration': 74,
95 'timestamp': 1425657362,
96 'upload_date': '20150306',
97 'uploader': 'IGN',
98 'uploader_id': 'xijv66',
99 'age_limit': 0,
100 'view_count': int,
101 },
102 'skip': 'video gone',
103 }, {
104 # Vevo video
105 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
106 'info_dict': {
107 'title': 'Roar (Official)',
108 'id': 'USUV71301934',
109 'ext': 'mp4',
110 'uploader': 'Katy Perry',
111 'upload_date': '20130905',
112 },
113 'params': {
114 'skip_download': True,
115 },
116 'skip': 'VEVO is only available in some countries',
117 }, {
118 # age-restricted video
119 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
120 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
121 'info_dict': {
122 'id': 'xyh2zz',
123 'ext': 'mp4',
124 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
125 'uploader': 'HotWaves1012',
126 'age_limit': 18,
127 },
128 'skip': 'video gone',
129 }, {
130 # geo-restricted, player v5
131 'url': 'http://www.dailymotion.com/video/xhza0o',
132 'only_matching': True,
133 }, {
134 # with subtitles
135 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
136 'only_matching': True,
137 }, {
138 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
139 'only_matching': True,
140 }, {
141 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
142 'only_matching': True,
143 }, {
144 'url': 'https://www.lequipe.fr/video/x791mem',
145 'only_matching': True,
146 }, {
147 'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2',
148 'only_matching': True,
149 }]
150
151 @staticmethod
152 def _extract_urls(webpage):
153 urls = []
154 # Look for embedded Dailymotion player
155 # https://developer.dailymotion.com/player#player-parameters
156 for mobj in re.finditer(
157 r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage):
158 urls.append(unescapeHTML(mobj.group('url')))
159 for mobj in re.finditer(
160 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s*:\s*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage):
161 urls.append('https://www.dailymotion.com/embed/video/' + mobj.group('id'))
162 return urls
163
164 def _real_extract(self, url):
165 video_id = self._match_id(url)
166
167 webpage = self._download_webpage_no_ff(
168 'https://www.dailymotion.com/video/%s' % video_id, video_id)
169
170 age_limit = self._rta_search(webpage)
171
172 description = self._og_search_description(
173 webpage, default=None) or self._html_search_meta(
174 'description', webpage, 'description')
175
176 view_count_str = self._search_regex(
177 (r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:([\s\d,.]+)"',
178 r'video_views_count[^>]+>\s+([\s\d\,.]+)'),
179 webpage, 'view count', default=None)
180 if view_count_str:
181 view_count_str = re.sub(r'\s', '', view_count_str)
182 view_count = str_to_int(view_count_str)
183 comment_count = int_or_none(self._search_regex(
184 r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
185 webpage, 'comment count', default=None))
186
187 player_v5 = self._search_regex(
188 [r'buildPlayer\(({.+?})\);\n', # See https://github.com/ytdl-org/youtube-dl/issues/7826
189 r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
190 r'buildPlayer\(({.+?})\);',
191 r'var\s+config\s*=\s*({.+?});',
192 # New layout regex (see https://github.com/ytdl-org/youtube-dl/issues/13580)
193 r'__PLAYER_CONFIG__\s*=\s*({.+?});'],
194 webpage, 'player v5', default=None)
195 if player_v5:
196 player = self._parse_json(player_v5, video_id, fatal=False) or {}
197 metadata = try_get(player, lambda x: x['metadata'], dict)
198 if not metadata:
199 metadata_url = url_or_none(try_get(
200 player, lambda x: x['context']['metadata_template_url1']))
201 if metadata_url:
202 metadata_url = metadata_url.replace(':videoId', video_id)
203 else:
204 metadata_url = update_url_query(
205 'https://www.dailymotion.com/player/metadata/video/%s'
206 % video_id, {
207 'embedder': url,
208 'integration': 'inline',
209 'GK_PV5_NEON': '1',
210 })
211 metadata = self._download_json(
212 metadata_url, video_id, 'Downloading metadata JSON')
213
214 if try_get(metadata, lambda x: x['error']['type']) == 'password_protected':
215 password = self._downloader.params.get('videopassword')
216 if password:
217 r = int(metadata['id'][1:], 36)
218 us64e = lambda x: base64.urlsafe_b64encode(x).decode().strip('=')
219 t = ''.join(random.choice(string.ascii_letters) for i in range(10))
220 n = us64e(compat_struct_pack('I', r))
221 i = us64e(hashlib.md5(('%s%d%s' % (password, r, t)).encode()).digest())
222 metadata = self._download_json(
223 'http://www.dailymotion.com/player/metadata/video/p' + i + t + n, video_id)
224
225 self._check_error(metadata)
226
227 formats = []
228 for quality, media_list in metadata['qualities'].items():
229 for media in media_list:
230 media_url = media.get('url')
231 if not media_url:
232 continue
233 type_ = media.get('type')
234 if type_ == 'application/vnd.lumberjack.manifest':
235 continue
236 ext = mimetype2ext(type_) or determine_ext(media_url)
237 if ext == 'm3u8':
238 m3u8_formats = self._extract_m3u8_formats(
239 media_url, video_id, 'mp4', preference=-1,
240 m3u8_id='hls', fatal=False)
241 for f in m3u8_formats:
242 f['url'] = f['url'].split('#')[0]
243 formats.append(f)
244 elif ext == 'f4m':
245 formats.extend(self._extract_f4m_formats(
246 media_url, video_id, preference=-1, f4m_id='hds', fatal=False))
247 else:
248 f = {
249 'url': media_url,
250 'format_id': 'http-%s' % quality,
251 'ext': ext,
252 }
253 m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
254 if m:
255 f.update({
256 'width': int(m.group('width')),
257 'height': int(m.group('height')),
258 })
259 formats.append(f)
260 self._sort_formats(formats)
261
262 title = metadata['title']
263 duration = int_or_none(metadata.get('duration'))
264 timestamp = int_or_none(metadata.get('created_time'))
265 thumbnail = metadata.get('poster_url')
266 uploader = metadata.get('owner', {}).get('screenname')
267 uploader_id = metadata.get('owner', {}).get('id')
268
269 subtitles = {}
270 subtitles_data = metadata.get('subtitles', {}).get('data', {})
271 if subtitles_data and isinstance(subtitles_data, dict):
272 for subtitle_lang, subtitle in subtitles_data.items():
273 subtitles[subtitle_lang] = [{
274 'ext': determine_ext(subtitle_url),
275 'url': subtitle_url,
276 } for subtitle_url in subtitle.get('urls', [])]
277
278 return {
279 'id': video_id,
280 'title': title,
281 'description': description,
282 'thumbnail': thumbnail,
283 'duration': duration,
284 'timestamp': timestamp,
285 'uploader': uploader,
286 'uploader_id': uploader_id,
287 'age_limit': age_limit,
288 'view_count': view_count,
289 'comment_count': comment_count,
290 'formats': formats,
291 'subtitles': subtitles,
292 }
293
294 # vevo embed
295 vevo_id = self._search_regex(
296 r'<link rel="video_src" href="[^"]*?vevo\.com[^"]*?video=(?P<id>[\w]*)',
297 webpage, 'vevo embed', default=None)
298 if vevo_id:
299 return self.url_result('vevo:%s' % vevo_id, 'Vevo')
300
301 # fallback old player
302 embed_page = self._download_webpage_no_ff(
303 'https://www.dailymotion.com/embed/video/%s' % video_id,
304 video_id, 'Downloading embed page')
305
306 timestamp = parse_iso8601(self._html_search_meta(
307 'video:release_date', webpage, 'upload date'))
308
309 info = self._parse_json(
310 self._search_regex(
311 r'var info = ({.*?}),$', embed_page,
312 'video info', flags=re.MULTILINE),
313 video_id)
314
315 self._check_error(info)
316
317 formats = []
318 for (key, format_id) in self._FORMATS:
319 video_url = info.get(key)
320 if video_url is not None:
321 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
322 if m_size is not None:
323 width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
324 else:
325 width, height = None, None
326 formats.append({
327 'url': video_url,
328 'ext': 'mp4',
329 'format_id': format_id,
330 'width': width,
331 'height': height,
332 })
333 self._sort_formats(formats)
334
335 # subtitles
336 video_subtitles = self.extract_subtitles(video_id, webpage)
337
338 title = self._og_search_title(webpage, default=None)
339 if title is None:
340 title = self._html_search_regex(
341 r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
342 'title')
343
344 return {
345 'id': video_id,
346 'formats': formats,
347 'uploader': info['owner.screenname'],
348 'timestamp': timestamp,
349 'title': title,
350 'description': description,
351 'subtitles': video_subtitles,
352 'thumbnail': info['thumbnail_url'],
353 'age_limit': age_limit,
354 'view_count': view_count,
355 'duration': info['duration']
356 }
357
358 def _check_error(self, info):
359 error = info.get('error')
360 if error:
361 title = error.get('title') or error['message']
362 # See https://developer.dailymotion.com/api#access-error
363 if error.get('code') == 'DM007':
364 self.raise_geo_restricted(msg=title)
365 raise ExtractorError(
366 '%s said: %s' % (self.IE_NAME, title), expected=True)
367
368 def _get_subtitles(self, video_id, webpage):
369 try:
370 sub_list = self._download_webpage(
371 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
372 video_id, note=False)
373 except ExtractorError as err:
374 self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
375 return {}
376 info = json.loads(sub_list)
377 if (info['total'] > 0):
378 sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
379 return sub_lang_list
380 self._downloader.report_warning('video doesn\'t have subtitles')
381 return {}
382
383
384 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
385 IE_NAME = 'dailymotion:playlist'
386 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
387 _TESTS = [{
388 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
389 'info_dict': {
390 'title': 'SPORT',
391 'id': 'xv4bw',
392 },
393 'playlist_mincount': 20,
394 }]
395 _PAGE_SIZE = 100
396
397 def _fetch_page(self, playlist_id, authorizaion, page):
398 page += 1
399 videos = self._download_json(
400 'https://graphql.api.dailymotion.com',
401 playlist_id, 'Downloading page %d' % page,
402 data=json.dumps({
403 'query': '''{
404 collection(xid: "%s") {
405 videos(first: %d, page: %d) {
406 pageInfo {
407 hasNextPage
408 nextPage
409 }
410 edges {
411 node {
412 xid
413 url
414 }
415 }
416 }
417 }
418 }''' % (playlist_id, self._PAGE_SIZE, page)
419 }).encode(), headers={
420 'Authorization': authorizaion,
421 'Origin': 'https://www.dailymotion.com',
422 })['data']['collection']['videos']
423 for edge in videos['edges']:
424 node = edge['node']
425 yield self.url_result(
426 node['url'], DailymotionIE.ie_key(), node['xid'])
427
428 def _real_extract(self, url):
429 playlist_id = self._match_id(url)
430 webpage = self._download_webpage(url, playlist_id)
431 api = self._parse_json(self._search_regex(
432 r'__PLAYER_CONFIG__\s*=\s*({.+?});',
433 webpage, 'player config'), playlist_id)['context']['api']
434 auth = self._download_json(
435 api.get('auth_url', 'https://graphql.api.dailymotion.com/oauth/token'),
436 playlist_id, data=urlencode_postdata({
437 'client_id': api.get('client_id', 'f1a362d288c1b98099c7'),
438 'client_secret': api.get('client_secret', 'eea605b96e01c796ff369935357eca920c5da4c5'),
439 'grant_type': 'client_credentials',
440 }))
441 authorizaion = '%s %s' % (auth.get('token_type', 'Bearer'), auth['access_token'])
442 entries = OnDemandPagedList(functools.partial(
443 self._fetch_page, playlist_id, authorizaion), self._PAGE_SIZE)
444 return self.playlist_result(
445 entries, playlist_id,
446 self._og_search_title(webpage))
447
448
449 class DailymotionUserIE(DailymotionBaseInfoExtractor):
450 IE_NAME = 'dailymotion:user'
451 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
452 _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
453 _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
454 _TESTS = [{
455 'url': 'https://www.dailymotion.com/user/nqtv',
456 'info_dict': {
457 'id': 'nqtv',
458 'title': 'Rémi Gaillard',
459 },
460 'playlist_mincount': 100,
461 }, {
462 'url': 'http://www.dailymotion.com/user/UnderProject',
463 'info_dict': {
464 'id': 'UnderProject',
465 'title': 'UnderProject',
466 },
467 'playlist_mincount': 1800,
468 'expected_warnings': [
469 'Stopped at duplicated page',
470 ],
471 'skip': 'Takes too long time',
472 }]
473
474 def _extract_entries(self, id):
475 video_ids = set()
476 processed_urls = set()
477 for pagenum in itertools.count(1):
478 page_url = self._PAGE_TEMPLATE % (id, pagenum)
479 webpage, urlh = self._download_webpage_handle_no_ff(
480 page_url, id, 'Downloading page %s' % pagenum)
481 if urlh.geturl() in processed_urls:
482 self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
483 page_url, urlh.geturl()), id)
484 break
485
486 processed_urls.add(urlh.geturl())
487
488 for video_id in re.findall(r'data-xid="(.+?)"', webpage):
489 if video_id not in video_ids:
490 yield self.url_result(
491 'http://www.dailymotion.com/video/%s' % video_id,
492 DailymotionIE.ie_key(), video_id)
493 video_ids.add(video_id)
494
495 if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
496 break
497
498 def _real_extract(self, url):
499 mobj = re.match(self._VALID_URL, url)
500 user = mobj.group('user')
501 webpage = self._download_webpage(
502 'https://www.dailymotion.com/user/%s' % user, user)
503 full_user = unescapeHTML(self._html_search_regex(
504 r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
505 webpage, 'user'))
506
507 return {
508 '_type': 'playlist',
509 'id': user,
510 'title': full_user,
511 'entries': self._extract_entries(user),
512 }