[XTubeIE] Add description to TEST
[youtube-dl] / youtube_dl / extractor / dailymotion.py
1 import re
2 import json
3 import itertools
4
5 from .common import InfoExtractor
6 from .subtitles import SubtitlesInfoExtractor
7
8 from ..utils import (
9     compat_urllib_request,
10     compat_str,
11     get_element_by_attribute,
12     get_element_by_id,
13     orderedSet,
14
15     ExtractorError,
16 )
17
18 class DailymotionBaseInfoExtractor(InfoExtractor):
19     @staticmethod
20     def _build_request(url):
21         """Build a request with the family filter disabled"""
22         request = compat_urllib_request.Request(url)
23         request.add_header('Cookie', 'family_filter=off')
24         return request
25
26 class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
27     """Information Extractor for Dailymotion"""
28
29     _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/(?:embed/)?video/([^/]+)'
30     IE_NAME = u'dailymotion'
31
32     _FORMATS = [
33         (u'stream_h264_ld_url', u'ld'),
34         (u'stream_h264_url', u'standard'),
35         (u'stream_h264_hq_url', u'hq'),
36         (u'stream_h264_hd_url', u'hd'),
37         (u'stream_h264_hd1080_url', u'hd180'),
38     ]
39
40     _TESTS = [
41         {
42             u'url': u'http://www.dailymotion.com/video/x33vw9_tutoriel-de-youtubeur-dl-des-video_tech',
43             u'file': u'x33vw9.mp4',
44             u'md5': u'392c4b85a60a90dc4792da41ce3144eb',
45             u'info_dict': {
46                 u"uploader": u"Amphora Alex and Van .", 
47                 u"title": u"Tutoriel de Youtubeur\"DL DES VIDEO DE YOUTUBE\""
48             }
49         },
50         # Vevo video
51         {
52             u'url': u'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
53             u'file': u'USUV71301934.mp4',
54             u'info_dict': {
55                 u'title': u'Roar (Official)',
56                 u'uploader': u'Katy Perry',
57                 u'upload_date': u'20130905',
58             },
59             u'params': {
60                 u'skip_download': True,
61             },
62             u'skip': u'VEVO is only available in some countries',
63         },
64     ]
65
66     def _real_extract(self, url):
67         # Extract id and simplified title from URL
68         mobj = re.match(self._VALID_URL, url)
69
70         video_id = mobj.group(1).split('_')[0].split('?')[0]
71
72         url = 'http://www.dailymotion.com/video/%s' % video_id
73
74         # Retrieve video webpage to extract further information
75         request = self._build_request(url)
76         webpage = self._download_webpage(request, video_id)
77
78         # Extract URL, uploader and title from webpage
79         self.report_extraction(video_id)
80
81         # It may just embed a vevo video:
82         m_vevo = re.search(
83             r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?videoId=(?P<id>[\w]*)',
84             webpage)
85         if m_vevo is not None:
86             vevo_id = m_vevo.group('id')
87             self.to_screen(u'Vevo video detected: %s' % vevo_id)
88             return self.url_result(u'vevo:%s' % vevo_id, ie='Vevo')
89
90         video_uploader = self._search_regex([r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>',
91                                              # Looking for official user
92                                              r'<(?:span|a) .*?rel="author".*?>([^<]+?)</'],
93                                             webpage, 'video uploader')
94
95         video_upload_date = None
96         mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
97         if mobj is not None:
98             video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
99
100         embed_url = 'http://www.dailymotion.com/embed/video/%s' % video_id
101         embed_page = self._download_webpage(embed_url, video_id,
102                                             u'Downloading embed page')
103         info = self._search_regex(r'var info = ({.*?}),$', embed_page,
104             'video info', flags=re.MULTILINE)
105         info = json.loads(info)
106         if info.get('error') is not None:
107             msg = 'Couldn\'t get video, Dailymotion says: %s' % info['error']['title']
108             raise ExtractorError(msg, expected=True)
109
110         formats = []
111         for (key, format_id) in self._FORMATS:
112             video_url = info.get(key)
113             if video_url is not None:
114                 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
115                 if m_size is not None:
116                     width, height = m_size.group(1), m_size.group(2)
117                 else:
118                     width, height = None, None
119                 formats.append({
120                     'url': video_url,
121                     'ext': 'mp4',
122                     'format_id': format_id,
123                     'width': width,
124                     'height': height,
125                 })
126         if not formats:
127             raise ExtractorError(u'Unable to extract video URL')
128
129         # subtitles
130         video_subtitles = self.extract_subtitles(video_id)
131         if self._downloader.params.get('listsubtitles', False):
132             self._list_available_subtitles(video_id)
133             return
134
135         return [{
136             'id':       video_id,
137             'formats': formats,
138             'uploader': video_uploader,
139             'upload_date':  video_upload_date,
140             'title':    self._og_search_title(webpage),
141             'subtitles':    video_subtitles,
142             'thumbnail': info['thumbnail_url']
143         }]
144
145     def _get_available_subtitles(self, video_id):
146         try:
147             sub_list = self._download_webpage(
148                 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
149                 video_id, note=False)
150         except ExtractorError as err:
151             self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
152             return {}
153         info = json.loads(sub_list)
154         if (info['total'] > 0):
155             sub_lang_list = dict((l['language'], l['url']) for l in info['list'])
156             return sub_lang_list
157         self._downloader.report_warning(u'video doesn\'t have subtitles')
158         return {}
159
160
161 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
162     IE_NAME = u'dailymotion:playlist'
163     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
164     _MORE_PAGES_INDICATOR = r'<div class="next">.*?<a.*?href="/playlist/.+?".*?>.*?</a>.*?</div>'
165     _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
166
167     def _extract_entries(self, id):
168         video_ids = []
169         for pagenum in itertools.count(1):
170             request = self._build_request(self._PAGE_TEMPLATE % (id, pagenum))
171             webpage = self._download_webpage(request,
172                                              id, u'Downloading page %s' % pagenum)
173
174             playlist_el = get_element_by_attribute(u'class', u'video_list', webpage)
175             video_ids.extend(re.findall(r'data-id="(.+?)"', playlist_el))
176
177             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
178                 break
179         return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
180                    for video_id in orderedSet(video_ids)]
181
182     def _real_extract(self, url):
183         mobj = re.match(self._VALID_URL, url)
184         playlist_id = mobj.group('id')
185         webpage = self._download_webpage(url, playlist_id)
186
187         return {'_type': 'playlist',
188                 'id': playlist_id,
189                 'title': get_element_by_id(u'playlist_name', webpage),
190                 'entries': self._extract_entries(playlist_id),
191                 }
192
193
194 class DailymotionUserIE(DailymotionPlaylistIE):
195     IE_NAME = u'dailymotion:user'
196     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/user/(?P<user>[^/]+)'
197     _MORE_PAGES_INDICATOR = r'<div class="next">.*?<a.*?href="/user/.+?".*?>.*?</a>.*?</div>'
198     _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
199
200     def _real_extract(self, url):
201         mobj = re.match(self._VALID_URL, url)
202         user = mobj.group('user')
203         webpage = self._download_webpage(url, user)
204         full_user = self._html_search_regex(
205             r'<a class="label" href="/%s".*?>(.*?)</' % re.escape(user),
206             webpage, u'user', flags=re.DOTALL)
207
208         return {
209             '_type': 'playlist',
210             'id': user,
211             'title': full_user,
212             'entries': self._extract_entries(user),
213         }