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