]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/dailymotion.py
Update README.md
[youtubedl] / youtube_dl / extractor / dailymotion.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import functools
5 import json
6 import re
7
8 from .common import InfoExtractor
9 from ..compat import compat_HTTPError
10 from ..utils import (
11 age_restricted,
12 clean_html,
13 ExtractorError,
14 int_or_none,
15 OnDemandPagedList,
16 try_get,
17 unescapeHTML,
18 urlencode_postdata,
19 )
20
21
22 class DailymotionBaseInfoExtractor(InfoExtractor):
23 _FAMILY_FILTER = None
24 _HEADERS = {
25 'Content-Type': 'application/json',
26 'Origin': 'https://www.dailymotion.com',
27 }
28 _NETRC_MACHINE = 'dailymotion'
29
30 def _get_dailymotion_cookies(self):
31 return self._get_cookies('https://www.dailymotion.com/')
32
33 @staticmethod
34 def _get_cookie_value(cookies, name):
35 cookie = cookies.get(name)
36 if cookie:
37 return cookie.value
38
39 def _set_dailymotion_cookie(self, name, value):
40 self._set_cookie('www.dailymotion.com', name, value)
41
42 def _real_initialize(self):
43 cookies = self._get_dailymotion_cookies()
44 ff = self._get_cookie_value(cookies, 'ff')
45 self._FAMILY_FILTER = ff == 'on' if ff else age_restricted(18, self._downloader.params.get('age_limit'))
46 self._set_dailymotion_cookie('ff', 'on' if self._FAMILY_FILTER else 'off')
47
48 def _call_api(self, object_type, xid, object_fields, note, filter_extra=None):
49 if not self._HEADERS.get('Authorization'):
50 cookies = self._get_dailymotion_cookies()
51 token = self._get_cookie_value(cookies, 'access_token') or self._get_cookie_value(cookies, 'client_token')
52 if not token:
53 data = {
54 'client_id': 'f1a362d288c1b98099c7',
55 'client_secret': 'eea605b96e01c796ff369935357eca920c5da4c5',
56 }
57 username, password = self._get_login_info()
58 if username:
59 data.update({
60 'grant_type': 'password',
61 'password': password,
62 'username': username,
63 })
64 else:
65 data['grant_type'] = 'client_credentials'
66 try:
67 token = self._download_json(
68 'https://graphql.api.dailymotion.com/oauth/token',
69 None, 'Downloading Access Token',
70 data=urlencode_postdata(data))['access_token']
71 except ExtractorError as e:
72 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
73 raise ExtractorError(self._parse_json(
74 e.cause.read().decode(), xid)['error_description'], expected=True)
75 raise
76 self._set_dailymotion_cookie('access_token' if username else 'client_token', token)
77 self._HEADERS['Authorization'] = 'Bearer ' + token
78
79 resp = self._download_json(
80 'https://graphql.api.dailymotion.com/', xid, note, data=json.dumps({
81 'query': '''{
82 %s(xid: "%s"%s) {
83 %s
84 }
85 }''' % (object_type, xid, ', ' + filter_extra if filter_extra else '', object_fields),
86 }).encode(), headers=self._HEADERS)
87 obj = resp['data'][object_type]
88 if not obj:
89 raise ExtractorError(resp['errors'][0]['message'], expected=True)
90 return obj
91
92
93 class DailymotionIE(DailymotionBaseInfoExtractor):
94 _VALID_URL = r'''(?ix)
95 https?://
96 (?:
97 (?:(?:www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|\#)/)?video|swf)|
98 (?:www\.)?lequipe\.fr/video
99 )
100 /(?P<id>[^/?_]+)(?:.+?\bplaylist=(?P<playlist_id>x[0-9a-z]+))?
101 '''
102 IE_NAME = 'dailymotion'
103 _TESTS = [{
104 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
105 'md5': '074b95bdee76b9e3654137aee9c79dfe',
106 'info_dict': {
107 'id': 'x5kesuj',
108 'ext': 'mp4',
109 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
110 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
111 'duration': 187,
112 'timestamp': 1493651285,
113 'upload_date': '20170501',
114 'uploader': 'Deadline',
115 'uploader_id': 'x1xm8ri',
116 'age_limit': 0,
117 },
118 }, {
119 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
120 'md5': '2137c41a8e78554bb09225b8eb322406',
121 'info_dict': {
122 'id': 'x2iuewm',
123 'ext': 'mp4',
124 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
125 'description': 'Several come bundled with the Steam Controller.',
126 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
127 'duration': 74,
128 'timestamp': 1425657362,
129 'upload_date': '20150306',
130 'uploader': 'IGN',
131 'uploader_id': 'xijv66',
132 'age_limit': 0,
133 'view_count': int,
134 },
135 'skip': 'video gone',
136 }, {
137 # Vevo video
138 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
139 'info_dict': {
140 'title': 'Roar (Official)',
141 'id': 'USUV71301934',
142 'ext': 'mp4',
143 'uploader': 'Katy Perry',
144 'upload_date': '20130905',
145 },
146 'params': {
147 'skip_download': True,
148 },
149 'skip': 'VEVO is only available in some countries',
150 }, {
151 # age-restricted video
152 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
153 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
154 'info_dict': {
155 'id': 'xyh2zz',
156 'ext': 'mp4',
157 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
158 'uploader': 'HotWaves1012',
159 'age_limit': 18,
160 },
161 'skip': 'video gone',
162 }, {
163 # geo-restricted, player v5
164 'url': 'http://www.dailymotion.com/video/xhza0o',
165 'only_matching': True,
166 }, {
167 # with subtitles
168 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
169 'only_matching': True,
170 }, {
171 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
172 'only_matching': True,
173 }, {
174 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
175 'only_matching': True,
176 }, {
177 'url': 'https://www.lequipe.fr/video/x791mem',
178 'only_matching': True,
179 }, {
180 'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2',
181 'only_matching': True,
182 }, {
183 'url': 'https://www.dailymotion.com/video/x3z49k?playlist=xv4bw',
184 'only_matching': True,
185 }]
186 _GEO_BYPASS = False
187 _COMMON_MEDIA_FIELDS = '''description
188 geoblockedCountries {
189 allowed
190 }
191 xid'''
192
193 @staticmethod
194 def _extract_urls(webpage):
195 urls = []
196 # Look for embedded Dailymotion player
197 # https://developer.dailymotion.com/player#player-parameters
198 for mobj in re.finditer(
199 r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage):
200 urls.append(unescapeHTML(mobj.group('url')))
201 for mobj in re.finditer(
202 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s*:\s*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage):
203 urls.append('https://www.dailymotion.com/embed/video/' + mobj.group('id'))
204 return urls
205
206 def _real_extract(self, url):
207 video_id, playlist_id = re.match(self._VALID_URL, url).groups()
208
209 if playlist_id:
210 if not self._downloader.params.get('noplaylist'):
211 self.to_screen('Downloading playlist %s - add --no-playlist to just download video' % playlist_id)
212 return self.url_result(
213 'http://www.dailymotion.com/playlist/' + playlist_id,
214 'DailymotionPlaylist', playlist_id)
215 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
216
217 password = self._downloader.params.get('videopassword')
218 media = self._call_api(
219 'media', video_id, '''... on Video {
220 %s
221 stats {
222 likes {
223 total
224 }
225 views {
226 total
227 }
228 }
229 }
230 ... on Live {
231 %s
232 audienceCount
233 isOnAir
234 }''' % (self._COMMON_MEDIA_FIELDS, self._COMMON_MEDIA_FIELDS), 'Downloading media JSON metadata',
235 'password: "%s"' % self._downloader.params.get('videopassword') if password else None)
236 xid = media['xid']
237
238 metadata = self._download_json(
239 'https://www.dailymotion.com/player/metadata/video/' + xid,
240 xid, 'Downloading metadata JSON',
241 query={'app': 'com.dailymotion.neon'})
242
243 error = metadata.get('error')
244 if error:
245 title = error.get('title') or error['raw_message']
246 # See https://developer.dailymotion.com/api#access-error
247 if error.get('code') == 'DM007':
248 allowed_countries = try_get(media, lambda x: x['geoblockedCountries']['allowed'], list)
249 self.raise_geo_restricted(msg=title, countries=allowed_countries)
250 raise ExtractorError(
251 '%s said: %s' % (self.IE_NAME, title), expected=True)
252
253 title = metadata['title']
254 is_live = media.get('isOnAir')
255 formats = []
256 for quality, media_list in metadata['qualities'].items():
257 for m in media_list:
258 media_url = m.get('url')
259 media_type = m.get('type')
260 if not media_url or media_type == 'application/vnd.lumberjack.manifest':
261 continue
262 if media_type == 'application/x-mpegURL':
263 formats.extend(self._extract_m3u8_formats(
264 media_url, video_id, 'mp4',
265 'm3u8' if is_live else 'm3u8_native',
266 m3u8_id='hls', fatal=False))
267 else:
268 f = {
269 'url': media_url,
270 'format_id': 'http-' + quality,
271 }
272 m = re.search(r'/H264-(\d+)x(\d+)(?:-(60)/)?', media_url)
273 if m:
274 width, height, fps = map(int_or_none, m.groups())
275 f.update({
276 'fps': fps,
277 'height': height,
278 'width': width,
279 })
280 formats.append(f)
281 for f in formats:
282 f['url'] = f['url'].split('#')[0]
283 if not f.get('fps') and f['format_id'].endswith('@60'):
284 f['fps'] = 60
285 self._sort_formats(formats)
286
287 subtitles = {}
288 subtitles_data = try_get(metadata, lambda x: x['subtitles']['data'], dict) or {}
289 for subtitle_lang, subtitle in subtitles_data.items():
290 subtitles[subtitle_lang] = [{
291 'url': subtitle_url,
292 } for subtitle_url in subtitle.get('urls', [])]
293
294 thumbnails = []
295 for height, poster_url in metadata.get('posters', {}).items():
296 thumbnails.append({
297 'height': int_or_none(height),
298 'id': height,
299 'url': poster_url,
300 })
301
302 owner = metadata.get('owner') or {}
303 stats = media.get('stats') or {}
304 get_count = lambda x: int_or_none(try_get(stats, lambda y: y[x + 's']['total']))
305
306 return {
307 'id': video_id,
308 'title': self._live_title(title) if is_live else title,
309 'description': clean_html(media.get('description')),
310 'thumbnails': thumbnails,
311 'duration': int_or_none(metadata.get('duration')) or None,
312 'timestamp': int_or_none(metadata.get('created_time')),
313 'uploader': owner.get('screenname'),
314 'uploader_id': owner.get('id') or metadata.get('screenname'),
315 'age_limit': 18 if metadata.get('explicit') else 0,
316 'tags': metadata.get('tags'),
317 'view_count': get_count('view') or int_or_none(media.get('audienceCount')),
318 'like_count': get_count('like'),
319 'formats': formats,
320 'subtitles': subtitles,
321 'is_live': is_live,
322 }
323
324
325 class DailymotionPlaylistBaseIE(DailymotionBaseInfoExtractor):
326 _PAGE_SIZE = 100
327
328 def _fetch_page(self, playlist_id, page):
329 page += 1
330 videos = self._call_api(
331 self._OBJECT_TYPE, playlist_id,
332 '''videos(allowExplicit: %s, first: %d, page: %d) {
333 edges {
334 node {
335 xid
336 url
337 }
338 }
339 }''' % ('false' if self._FAMILY_FILTER else 'true', self._PAGE_SIZE, page),
340 'Downloading page %d' % page)['videos']
341 for edge in videos['edges']:
342 node = edge['node']
343 yield self.url_result(
344 node['url'], DailymotionIE.ie_key(), node['xid'])
345
346 def _real_extract(self, url):
347 playlist_id = self._match_id(url)
348 entries = OnDemandPagedList(functools.partial(
349 self._fetch_page, playlist_id), self._PAGE_SIZE)
350 return self.playlist_result(
351 entries, playlist_id)
352
353
354 class DailymotionPlaylistIE(DailymotionPlaylistBaseIE):
355 IE_NAME = 'dailymotion:playlist'
356 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
357 _TESTS = [{
358 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
359 'info_dict': {
360 'id': 'xv4bw',
361 },
362 'playlist_mincount': 20,
363 }]
364 _OBJECT_TYPE = 'collection'
365
366
367 class DailymotionUserIE(DailymotionPlaylistBaseIE):
368 IE_NAME = 'dailymotion:user'
369 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<id>[^/]+)'
370 _TESTS = [{
371 'url': 'https://www.dailymotion.com/user/nqtv',
372 'info_dict': {
373 'id': 'nqtv',
374 },
375 'playlist_mincount': 152,
376 }, {
377 'url': 'http://www.dailymotion.com/user/UnderProject',
378 'info_dict': {
379 'id': 'UnderProject',
380 },
381 'playlist_mincount': 1000,
382 'skip': 'Takes too long time',
383 }, {
384 'url': 'https://www.dailymotion.com/user/nqtv',
385 'info_dict': {
386 'id': 'nqtv',
387 },
388 'playlist_mincount': 148,
389 'params': {
390 'age_limit': 0,
391 },
392 }]
393 _OBJECT_TYPE = 'channel'