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