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