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