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