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