]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/ard.py
New upstream version 2017.12.31
[youtubedl] / youtube_dl / extractor / ard.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from .generic import GenericIE
8 from ..compat import compat_str
9 from ..utils import (
10 determine_ext,
11 ExtractorError,
12 qualities,
13 int_or_none,
14 parse_duration,
15 unified_strdate,
16 xpath_text,
17 update_url_query,
18 )
19 from ..compat import compat_etree_fromstring
20
21
22 class ARDMediathekIE(InfoExtractor):
23 IE_NAME = 'ARD:mediathek'
24 _VALID_URL = r'^https?://(?:(?:www\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
25
26 _TESTS = [{
27 'url': 'http://www.ardmediathek.de/tv/Dokumentation-und-Reportage/Ich-liebe-das-Leben-trotzdem/rbb-Fernsehen/Video?documentId=29582122&bcastId=3822114',
28 'info_dict': {
29 'id': '29582122',
30 'ext': 'mp4',
31 'title': 'Ich liebe das Leben trotzdem',
32 'description': 'md5:45e4c225c72b27993314b31a84a5261c',
33 'duration': 4557,
34 },
35 'params': {
36 # m3u8 download
37 'skip_download': True,
38 },
39 'skip': 'HTTP Error 404: Not Found',
40 }, {
41 'url': 'http://www.ardmediathek.de/tv/Tatort/Tatort-Scheinwelten-H%C3%B6rfassung-Video/Das-Erste/Video?documentId=29522730&bcastId=602916',
42 'md5': 'f4d98b10759ac06c0072bbcd1f0b9e3e',
43 'info_dict': {
44 'id': '29522730',
45 'ext': 'mp4',
46 'title': 'Tatort: Scheinwelten - Hörfassung (Video tgl. ab 20 Uhr)',
47 'description': 'md5:196392e79876d0ac94c94e8cdb2875f1',
48 'duration': 5252,
49 },
50 'skip': 'HTTP Error 404: Not Found',
51 }, {
52 # audio
53 'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
54 'md5': '219d94d8980b4f538c7fcb0865eb7f2c',
55 'info_dict': {
56 'id': '28488308',
57 'ext': 'mp3',
58 'title': 'Tod eines Fußballers',
59 'description': 'md5:f6e39f3461f0e1f54bfa48c8875c86ef',
60 'duration': 3240,
61 },
62 'skip': 'HTTP Error 404: Not Found',
63 }, {
64 'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
65 'only_matching': True,
66 }, {
67 # audio
68 'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158',
69 'md5': '4e8f00631aac0395fee17368ac0e9867',
70 'info_dict': {
71 'id': '30796318',
72 'ext': 'mp3',
73 'title': 'Vor dem Fest',
74 'description': 'md5:c0c1c8048514deaed2a73b3a60eecacb',
75 'duration': 3287,
76 },
77 'skip': 'Video is no longer available',
78 }]
79
80 def _extract_media_info(self, media_info_url, webpage, video_id):
81 media_info = self._download_json(
82 media_info_url, video_id, 'Downloading media JSON')
83
84 formats = self._extract_formats(media_info, video_id)
85
86 if not formats:
87 if '"fsk"' in webpage:
88 raise ExtractorError(
89 'This video is only available after 20:00', expected=True)
90 elif media_info.get('_geoblocked'):
91 raise ExtractorError('This video is not available due to geo restriction', expected=True)
92
93 self._sort_formats(formats)
94
95 duration = int_or_none(media_info.get('_duration'))
96 thumbnail = media_info.get('_previewImage')
97 is_live = media_info.get('_isLive') is True
98
99 subtitles = {}
100 subtitle_url = media_info.get('_subtitleUrl')
101 if subtitle_url:
102 subtitles['de'] = [{
103 'ext': 'ttml',
104 'url': subtitle_url,
105 }]
106
107 return {
108 'id': video_id,
109 'duration': duration,
110 'thumbnail': thumbnail,
111 'is_live': is_live,
112 'formats': formats,
113 'subtitles': subtitles,
114 }
115
116 def _extract_formats(self, media_info, video_id):
117 type_ = media_info.get('_type')
118 media_array = media_info.get('_mediaArray', [])
119 formats = []
120 for num, media in enumerate(media_array):
121 for stream in media.get('_mediaStreamArray', []):
122 stream_urls = stream.get('_stream')
123 if not stream_urls:
124 continue
125 if not isinstance(stream_urls, list):
126 stream_urls = [stream_urls]
127 quality = stream.get('_quality')
128 server = stream.get('_server')
129 for stream_url in stream_urls:
130 if not isinstance(stream_url, compat_str) or '//' not in stream_url:
131 continue
132 ext = determine_ext(stream_url)
133 if quality != 'auto' and ext in ('f4m', 'm3u8'):
134 continue
135 if ext == 'f4m':
136 formats.extend(self._extract_f4m_formats(
137 update_url_query(stream_url, {
138 'hdcore': '3.1.1',
139 'plugin': 'aasp-3.1.1.69.124'
140 }),
141 video_id, f4m_id='hds', fatal=False))
142 elif ext == 'm3u8':
143 formats.extend(self._extract_m3u8_formats(
144 stream_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
145 else:
146 if server and server.startswith('rtmp'):
147 f = {
148 'url': server,
149 'play_path': stream_url,
150 'format_id': 'a%s-rtmp-%s' % (num, quality),
151 }
152 else:
153 f = {
154 'url': stream_url,
155 'format_id': 'a%s-%s-%s' % (num, ext, quality)
156 }
157 m = re.search(r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$', stream_url)
158 if m:
159 f.update({
160 'width': int(m.group('width')),
161 'height': int(m.group('height')),
162 })
163 if type_ == 'audio':
164 f['vcodec'] = 'none'
165 formats.append(f)
166 return formats
167
168 def _real_extract(self, url):
169 # determine video id from url
170 m = re.match(self._VALID_URL, url)
171
172 document_id = None
173
174 numid = re.search(r'documentId=([0-9]+)', url)
175 if numid:
176 document_id = video_id = numid.group(1)
177 else:
178 video_id = m.group('video_id')
179
180 webpage = self._download_webpage(url, video_id)
181
182 ERRORS = (
183 ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'),
184 ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<',
185 'Video %s is no longer available'),
186 )
187
188 for pattern, message in ERRORS:
189 if pattern in webpage:
190 raise ExtractorError(message % video_id, expected=True)
191
192 if re.search(r'[\?&]rss($|[=&])', url):
193 doc = compat_etree_fromstring(webpage.encode('utf-8'))
194 if doc.tag == 'rss':
195 return GenericIE()._extract_rss(url, video_id, doc)
196
197 title = self._html_search_regex(
198 [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
199 r'<meta name="dcterms\.title" content="(.*?)"/>',
200 r'<h4 class="headline">(.*?)</h4>'],
201 webpage, 'title')
202 description = self._html_search_meta(
203 'dcterms.abstract', webpage, 'description', default=None)
204 if description is None:
205 description = self._html_search_meta(
206 'description', webpage, 'meta description')
207
208 # Thumbnail is sometimes not present.
209 # It is in the mobile version, but that seems to use a different URL
210 # structure altogether.
211 thumbnail = self._og_search_thumbnail(webpage, default=None)
212
213 media_streams = re.findall(r'''(?x)
214 mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
215 "([^"]+)"''', webpage)
216
217 if media_streams:
218 QUALITIES = qualities(['lo', 'hi', 'hq'])
219 formats = []
220 for furl in set(media_streams):
221 if furl.endswith('.f4m'):
222 fid = 'f4m'
223 else:
224 fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
225 fid = fid_m.group(1) if fid_m else None
226 formats.append({
227 'quality': QUALITIES(fid),
228 'format_id': fid,
229 'url': furl,
230 })
231 self._sort_formats(formats)
232 info = {
233 'formats': formats,
234 }
235 else: # request JSON file
236 if not document_id:
237 video_id = self._search_regex(
238 r'/play/(?:config|media)/(\d+)', webpage, 'media id')
239 info = self._extract_media_info(
240 'http://www.ardmediathek.de/play/media/%s' % video_id,
241 webpage, video_id)
242
243 info.update({
244 'id': video_id,
245 'title': self._live_title(title) if info.get('is_live') else title,
246 'description': description,
247 'thumbnail': thumbnail,
248 })
249
250 return info
251
252
253 class ARDIE(InfoExtractor):
254 _VALID_URL = r'(?P<mainurl>https?://(www\.)?daserste\.de/[^?#]+/videos/(?P<display_id>[^/?#]+)-(?P<id>[0-9]+))\.html'
255 _TEST = {
256 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
257 'md5': 'd216c3a86493f9322545e045ddc3eb35',
258 'info_dict': {
259 'display_id': 'die-story-im-ersten-mission-unter-falscher-flagge',
260 'id': '100',
261 'ext': 'mp4',
262 'duration': 2600,
263 'title': 'Die Story im Ersten: Mission unter falscher Flagge',
264 'upload_date': '20140804',
265 'thumbnail': r're:^https?://.*\.jpg$',
266 },
267 'skip': 'HTTP Error 404: Not Found',
268 }
269
270 def _real_extract(self, url):
271 mobj = re.match(self._VALID_URL, url)
272 display_id = mobj.group('display_id')
273
274 player_url = mobj.group('mainurl') + '~playerXml.xml'
275 doc = self._download_xml(player_url, display_id)
276 video_node = doc.find('./video')
277 upload_date = unified_strdate(xpath_text(
278 video_node, './broadcastDate'))
279 thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
280
281 formats = []
282 for a in video_node.findall('.//asset'):
283 f = {
284 'format_id': a.attrib['type'],
285 'width': int_or_none(a.find('./frameWidth').text),
286 'height': int_or_none(a.find('./frameHeight').text),
287 'vbr': int_or_none(a.find('./bitrateVideo').text),
288 'abr': int_or_none(a.find('./bitrateAudio').text),
289 'vcodec': a.find('./codecVideo').text,
290 'tbr': int_or_none(a.find('./totalBitrate').text),
291 }
292 if a.find('./serverPrefix').text:
293 f['url'] = a.find('./serverPrefix').text
294 f['playpath'] = a.find('./fileName').text
295 else:
296 f['url'] = a.find('./fileName').text
297 formats.append(f)
298 self._sort_formats(formats)
299
300 return {
301 'id': mobj.group('id'),
302 'formats': formats,
303 'display_id': display_id,
304 'title': video_node.find('./title').text,
305 'duration': parse_duration(video_node.find('./duration').text),
306 'upload_date': upload_date,
307 'thumbnail': thumbnail,
308 }