]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/dailymotion.py
[SpankBang] Use python2.6 compatible string formatting spec
[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     int_or_none,
17     orderedSet,
18     str_to_int,
19     unescapeHTML,
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 = compat_urllib_request.Request(url)
28         request.add_header('Cookie', 'family_filter=off; ff=off')
29         return request
30
31
32 class DailymotionIE(DailymotionBaseInfoExtractor):
33     """Information Extractor for Dailymotion"""
34
35     _VALID_URL = r'(?i)(?:https?://)?(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(embed|#)/)?video/(?P<id>[^/?_]+)'
36     IE_NAME = 'dailymotion'
37
38     _FORMATS = [
39         ('stream_h264_ld_url', 'ld'),
40         ('stream_h264_url', 'standard'),
41         ('stream_h264_hq_url', 'hq'),
42         ('stream_h264_hd_url', 'hd'),
43         ('stream_h264_hd1080_url', 'hd180'),
44     ]
45
46     _TESTS = [
47         {
48             'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
49             'md5': '2137c41a8e78554bb09225b8eb322406',
50             'info_dict': {
51                 'id': 'x2iuewm',
52                 'ext': 'mp4',
53                 'uploader': 'IGN',
54                 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
55             }
56         },
57         # Vevo video
58         {
59             'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
60             'info_dict': {
61                 'title': 'Roar (Official)',
62                 'id': 'USUV71301934',
63                 'ext': 'mp4',
64                 'uploader': 'Katy Perry',
65                 'upload_date': '20130905',
66             },
67             'params': {
68                 'skip_download': True,
69             },
70             'skip': 'VEVO is only available in some countries',
71         },
72         # age-restricted video
73         {
74             'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
75             'md5': '0d667a7b9cebecc3c89ee93099c4159d',
76             'info_dict': {
77                 'id': 'xyh2zz',
78                 'ext': 'mp4',
79                 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
80                 'uploader': 'HotWaves1012',
81                 'age_limit': 18,
82             }
83         }
84     ]
85
86     def _real_extract(self, url):
87         video_id = self._match_id(url)
88         url = 'http://www.dailymotion.com/video/%s' % video_id
89
90         # Retrieve video webpage to extract further information
91         request = self._build_request(url)
92         webpage = self._download_webpage(request, video_id)
93
94         # Extract URL, uploader and title from webpage
95         self.report_extraction(video_id)
96
97         # It may just embed a vevo video:
98         m_vevo = re.search(
99             r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?video=(?P<id>[\w]*)',
100             webpage)
101         if m_vevo is not None:
102             vevo_id = m_vevo.group('id')
103             self.to_screen('Vevo video detected: %s' % vevo_id)
104             return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
105
106         age_limit = self._rta_search(webpage)
107
108         video_upload_date = None
109         mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
110         if mobj is not None:
111             video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
112
113         embed_url = 'http://www.dailymotion.com/embed/video/%s' % video_id
114         embed_request = self._build_request(embed_url)
115         embed_page = self._download_webpage(
116             embed_request, video_id, 'Downloading embed page')
117         info = self._search_regex(r'var info = ({.*?}),$', embed_page,
118                                   'video info', flags=re.MULTILINE)
119         info = json.loads(info)
120         if info.get('error') is not None:
121             msg = 'Couldn\'t get video, Dailymotion says: %s' % info['error']['title']
122             raise ExtractorError(msg, expected=True)
123
124         formats = []
125         for (key, format_id) in self._FORMATS:
126             video_url = info.get(key)
127             if video_url is not None:
128                 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
129                 if m_size is not None:
130                     width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
131                 else:
132                     width, height = None, None
133                 formats.append({
134                     'url': video_url,
135                     'ext': 'mp4',
136                     'format_id': format_id,
137                     'width': width,
138                     'height': height,
139                 })
140         if not formats:
141             raise ExtractorError('Unable to extract video URL')
142
143         # subtitles
144         video_subtitles = self.extract_subtitles(video_id, webpage)
145
146         view_count = str_to_int(self._search_regex(
147             r'video_views_count[^>]+>\s+([\d\.,]+)',
148             webpage, 'view count', fatal=False))
149
150         title = self._og_search_title(webpage, default=None)
151         if title is None:
152             title = self._html_search_regex(
153                 r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
154                 'title')
155
156         return {
157             'id': video_id,
158             'formats': formats,
159             'uploader': info['owner.screenname'],
160             'upload_date': video_upload_date,
161             'title': title,
162             'subtitles': video_subtitles,
163             'thumbnail': info['thumbnail_url'],
164             'age_limit': age_limit,
165             'view_count': view_count,
166         }
167
168     def _get_subtitles(self, video_id, webpage):
169         try:
170             sub_list = self._download_webpage(
171                 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
172                 video_id, note=False)
173         except ExtractorError as err:
174             self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
175             return {}
176         info = json.loads(sub_list)
177         if (info['total'] > 0):
178             sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
179             return sub_lang_list
180         self._downloader.report_warning('video doesn\'t have subtitles')
181         return {}
182
183
184 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
185     IE_NAME = 'dailymotion:playlist'
186     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
187     _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
188     _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
189     _TESTS = [{
190         'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
191         'info_dict': {
192             'title': 'SPORT',
193             'id': 'xv4bw_nqtv_sport',
194         },
195         'playlist_mincount': 20,
196     }]
197
198     def _extract_entries(self, id):
199         video_ids = []
200         for pagenum in itertools.count(1):
201             request = self._build_request(self._PAGE_TEMPLATE % (id, pagenum))
202             webpage = self._download_webpage(request,
203                                              id, 'Downloading page %s' % pagenum)
204
205             video_ids.extend(re.findall(r'data-xid="(.+?)"', webpage))
206
207             if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
208                 break
209         return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
210                 for video_id in orderedSet(video_ids)]
211
212     def _real_extract(self, url):
213         mobj = re.match(self._VALID_URL, url)
214         playlist_id = mobj.group('id')
215         webpage = self._download_webpage(url, playlist_id)
216
217         return {
218             '_type': 'playlist',
219             'id': playlist_id,
220             'title': self._og_search_title(webpage),
221             'entries': self._extract_entries(playlist_id),
222         }
223
224
225 class DailymotionUserIE(DailymotionPlaylistIE):
226     IE_NAME = 'dailymotion:user'
227     _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/user/(?P<user>[^/]+)'
228     _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
229     _TESTS = [{
230         'url': 'https://www.dailymotion.com/user/nqtv',
231         'info_dict': {
232             'id': 'nqtv',
233             'title': 'RĂ©mi Gaillard',
234         },
235         'playlist_mincount': 100,
236     }]
237
238     def _real_extract(self, url):
239         mobj = re.match(self._VALID_URL, url)
240         user = mobj.group('user')
241         webpage = self._download_webpage(url, user)
242         full_user = unescapeHTML(self._html_search_regex(
243             r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
244             webpage, 'user'))
245
246         return {
247             '_type': 'playlist',
248             'id': user,
249             'title': full_user,
250             'entries': self._extract_entries(user),
251         }