Merge remote-tracking branch 'rzhxeo/RTL_T'
[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
14     ExtractorError,
15 )
16
17
18 class DailymotionIE(SubtitlesInfoExtractor):
19     """Information Extractor for Dailymotion"""
20
21     _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/(?:embed/)?video/([^/]+)'
22     IE_NAME = u'dailymotion'
23     _TEST = {
24         u'url': u'http://www.dailymotion.com/video/x33vw9_tutoriel-de-youtubeur-dl-des-video_tech',
25         u'file': u'x33vw9.mp4',
26         u'md5': u'392c4b85a60a90dc4792da41ce3144eb',
27         u'info_dict': {
28             u"uploader": u"Amphora Alex and Van .", 
29             u"title": u"Tutoriel de Youtubeur\"DL DES VIDEO DE YOUTUBE\""
30         }
31     }
32
33     def _real_extract(self, url):
34         # Extract id and simplified title from URL
35         mobj = re.match(self._VALID_URL, url)
36
37         video_id = mobj.group(1).split('_')[0].split('?')[0]
38
39         video_extension = 'mp4'
40         url = 'http://www.dailymotion.com/video/%s' % video_id
41
42         # Retrieve video webpage to extract further information
43         request = compat_urllib_request.Request(url)
44         request.add_header('Cookie', 'family_filter=off')
45         webpage = self._download_webpage(request, video_id)
46
47         # Extract URL, uploader and title from webpage
48         self.report_extraction(video_id)
49
50         video_uploader = self._search_regex([r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>',
51                                              # Looking for official user
52                                              r'<(?:span|a) .*?rel="author".*?>([^<]+?)</'],
53                                             webpage, 'video uploader')
54
55         video_upload_date = None
56         mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
57         if mobj is not None:
58             video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
59
60         embed_url = 'http://www.dailymotion.com/embed/video/%s' % video_id
61         embed_page = self._download_webpage(embed_url, video_id,
62                                             u'Downloading embed page')
63         info = self._search_regex(r'var info = ({.*?}),$', embed_page,
64             'video info', flags=re.MULTILINE)
65         info = json.loads(info)
66         if info.get('error') is not None:
67             msg = 'Couldn\'t get video, Dailymotion says: %s' % info['error']['title']
68             raise ExtractorError(msg, expected=True)
69
70         # TODO: support choosing qualities
71
72         for key in ['stream_h264_hd1080_url','stream_h264_hd_url',
73                     'stream_h264_hq_url','stream_h264_url',
74                     'stream_h264_ld_url']:
75             if info.get(key):#key in info and info[key]:
76                 max_quality = key
77                 self.to_screen(u'Using %s' % key)
78                 break
79         else:
80             raise ExtractorError(u'Unable to extract video URL')
81         video_url = info[max_quality]
82
83         # subtitles
84         video_subtitles = self.extract_subtitles(video_id)
85         if self._downloader.params.get('listsubtitles', False):
86             self._list_available_subtitles(video_id)
87             return
88
89         return [{
90             'id':       video_id,
91             'url':      video_url,
92             'uploader': video_uploader,
93             'upload_date':  video_upload_date,
94             'title':    self._og_search_title(webpage),
95             'ext':      video_extension,
96             'subtitles':    video_subtitles,
97             'thumbnail': info['thumbnail_url']
98         }]
99
100     def _get_available_subtitles(self, video_id):
101         try:
102             sub_list = self._download_webpage(
103                 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
104                 video_id, note=False)
105         except ExtractorError as err:
106             self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
107             return {}
108         info = json.loads(sub_list)
109         if (info['total'] > 0):
110             sub_lang_list = dict((l['language'], l['url']) for l in info['list'])
111             return sub_lang_list
112         self._downloader.report_warning(u'video doesn\'t have subtitles')
113         return {}
114
115
116 class DailymotionPlaylistIE(InfoExtractor):
117     IE_NAME = u'dailymotion:playlist'
118     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
119     _MORE_PAGES_INDICATOR = r'<div class="next">.*?<a.*?href="/playlist/.+?".*?>.*?</a>.*?</div>'
120     _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
121
122     def _extract_entries(self, id):
123         video_ids = []
124         for pagenum in itertools.count(1):
125             webpage = self._download_webpage(self._PAGE_TEMPLATE % (id, pagenum),
126                                              id, u'Downloading page %s' % pagenum)
127
128             playlist_el = get_element_by_attribute(u'class', u'video_list', webpage)
129             video_ids.extend(re.findall(r'data-id="(.+?)" data-ext-id', playlist_el))
130
131             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
132                 break
133         return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
134                    for video_id in video_ids]
135
136     def _real_extract(self, url):
137         mobj = re.match(self._VALID_URL, url)
138         playlist_id = mobj.group('id')
139         webpage = self._download_webpage(url, playlist_id)
140
141         return {'_type': 'playlist',
142                 'id': playlist_id,
143                 'title': get_element_by_id(u'playlist_name', webpage),
144                 'entries': self._extract_entries(playlist_id),
145                 }
146
147
148 class DailymotionUserIE(DailymotionPlaylistIE):
149     IE_NAME = u'dailymotion:user'
150     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/user/(?P<user>[^/]+)'
151     _MORE_PAGES_INDICATOR = r'<div class="next">.*?<a.*?href="/user/.+?".*?>.*?</a>.*?</div>'
152     _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
153
154     def _real_extract(self, url):
155         mobj = re.match(self._VALID_URL, url)
156         user = mobj.group('user')
157         webpage = self._download_webpage(url, user)
158         full_user = self._html_search_regex(
159             r'<a class="label" href="/%s".*?>(.*?)</' % re.escape(user),
160             webpage, u'user', flags=re.DOTALL)
161
162         return {
163             '_type': 'playlist',
164             'id': user,
165             'title': full_user,
166             'entries': self._extract_entries(user),
167         }