[ard:beta] Relax _VALID_URL (closes #18441)
[youtube-dl] / 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 ..utils import (
9     determine_ext,
10     ExtractorError,
11     qualities,
12     int_or_none,
13     parse_duration,
14     unified_strdate,
15     xpath_text,
16     update_url_query,
17     url_or_none,
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|classic)\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de|one\.ard\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
25
26     _TESTS = [{
27         # available till 26.07.2022
28         'url': 'http://www.ardmediathek.de/tv/S%C3%9CDLICHT/Was-ist-die-Kunst-der-Zukunft-liebe-Ann/BR-Fernsehen/Video?bcastId=34633636&documentId=44726822',
29         'info_dict': {
30             'id': '44726822',
31             'ext': 'mp4',
32             'title': 'Was ist die Kunst der Zukunft, liebe Anna McCarthy?',
33             'description': 'md5:4ada28b3e3b5df01647310e41f3a62f5',
34             'duration': 1740,
35         },
36         'params': {
37             # m3u8 download
38             'skip_download': True,
39         }
40     }, {
41         'url': 'https://one.ard.de/tv/Mord-mit-Aussicht/Mord-mit-Aussicht-6-39-T%C3%B6dliche-Nach/ONE/Video?bcastId=46384294&documentId=55586872',
42         'only_matching': True,
43     }, {
44         # audio
45         'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
46         'only_matching': True,
47     }, {
48         'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
49         'only_matching': True,
50     }, {
51         # audio
52         'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158',
53         'only_matching': True,
54     }, {
55         'url': 'https://classic.ardmediathek.de/tv/Panda-Gorilla-Co/Panda-Gorilla-Co-Folge-274/Das-Erste/Video?bcastId=16355486&documentId=58234698',
56         'only_matching': True,
57     }]
58
59     @classmethod
60     def suitable(cls, url):
61         return False if ARDBetaMediathekIE.suitable(url) else super(ARDMediathekIE, cls).suitable(url)
62
63     def _extract_media_info(self, media_info_url, webpage, video_id):
64         media_info = self._download_json(
65             media_info_url, video_id, 'Downloading media JSON')
66
67         formats = self._extract_formats(media_info, video_id)
68
69         if not formats:
70             if '"fsk"' in webpage:
71                 raise ExtractorError(
72                     'This video is only available after 20:00', expected=True)
73             elif media_info.get('_geoblocked'):
74                 raise ExtractorError('This video is not available due to geo restriction', expected=True)
75
76         self._sort_formats(formats)
77
78         duration = int_or_none(media_info.get('_duration'))
79         thumbnail = media_info.get('_previewImage')
80         is_live = media_info.get('_isLive') is True
81
82         subtitles = {}
83         subtitle_url = media_info.get('_subtitleUrl')
84         if subtitle_url:
85             subtitles['de'] = [{
86                 'ext': 'ttml',
87                 'url': subtitle_url,
88             }]
89
90         return {
91             'id': video_id,
92             'duration': duration,
93             'thumbnail': thumbnail,
94             'is_live': is_live,
95             'formats': formats,
96             'subtitles': subtitles,
97         }
98
99     def _extract_formats(self, media_info, video_id):
100         type_ = media_info.get('_type')
101         media_array = media_info.get('_mediaArray', [])
102         formats = []
103         for num, media in enumerate(media_array):
104             for stream in media.get('_mediaStreamArray', []):
105                 stream_urls = stream.get('_stream')
106                 if not stream_urls:
107                     continue
108                 if not isinstance(stream_urls, list):
109                     stream_urls = [stream_urls]
110                 quality = stream.get('_quality')
111                 server = stream.get('_server')
112                 for stream_url in stream_urls:
113                     if not url_or_none(stream_url):
114                         continue
115                     ext = determine_ext(stream_url)
116                     if quality != 'auto' and ext in ('f4m', 'm3u8'):
117                         continue
118                     if ext == 'f4m':
119                         formats.extend(self._extract_f4m_formats(
120                             update_url_query(stream_url, {
121                                 'hdcore': '3.1.1',
122                                 'plugin': 'aasp-3.1.1.69.124'
123                             }),
124                             video_id, f4m_id='hds', fatal=False))
125                     elif ext == 'm3u8':
126                         formats.extend(self._extract_m3u8_formats(
127                             stream_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
128                     else:
129                         if server and server.startswith('rtmp'):
130                             f = {
131                                 'url': server,
132                                 'play_path': stream_url,
133                                 'format_id': 'a%s-rtmp-%s' % (num, quality),
134                             }
135                         else:
136                             f = {
137                                 'url': stream_url,
138                                 'format_id': 'a%s-%s-%s' % (num, ext, quality)
139                             }
140                         m = re.search(r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$', stream_url)
141                         if m:
142                             f.update({
143                                 'width': int(m.group('width')),
144                                 'height': int(m.group('height')),
145                             })
146                         if type_ == 'audio':
147                             f['vcodec'] = 'none'
148                         formats.append(f)
149         return formats
150
151     def _real_extract(self, url):
152         # determine video id from url
153         m = re.match(self._VALID_URL, url)
154
155         document_id = None
156
157         numid = re.search(r'documentId=([0-9]+)', url)
158         if numid:
159             document_id = video_id = numid.group(1)
160         else:
161             video_id = m.group('video_id')
162
163         webpage = self._download_webpage(url, video_id)
164
165         ERRORS = (
166             ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'),
167             ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<',
168              'Video %s is no longer available'),
169         )
170
171         for pattern, message in ERRORS:
172             if pattern in webpage:
173                 raise ExtractorError(message % video_id, expected=True)
174
175         if re.search(r'[\?&]rss($|[=&])', url):
176             doc = compat_etree_fromstring(webpage.encode('utf-8'))
177             if doc.tag == 'rss':
178                 return GenericIE()._extract_rss(url, video_id, doc)
179
180         title = self._html_search_regex(
181             [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
182              r'<meta name="dcterms\.title" content="(.*?)"/>',
183              r'<h4 class="headline">(.*?)</h4>',
184              r'<title[^>]*>(.*?)</title>'],
185             webpage, 'title')
186         description = self._html_search_meta(
187             'dcterms.abstract', webpage, 'description', default=None)
188         if description is None:
189             description = self._html_search_meta(
190                 'description', webpage, 'meta description', default=None)
191         if description is None:
192             description = self._html_search_regex(
193                 r'<p\s+class="teasertext">(.+?)</p>',
194                 webpage, 'teaser text', default=None)
195
196         # Thumbnail is sometimes not present.
197         # It is in the mobile version, but that seems to use a different URL
198         # structure altogether.
199         thumbnail = self._og_search_thumbnail(webpage, default=None)
200
201         media_streams = re.findall(r'''(?x)
202             mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
203             "([^"]+)"''', webpage)
204
205         if media_streams:
206             QUALITIES = qualities(['lo', 'hi', 'hq'])
207             formats = []
208             for furl in set(media_streams):
209                 if furl.endswith('.f4m'):
210                     fid = 'f4m'
211                 else:
212                     fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
213                     fid = fid_m.group(1) if fid_m else None
214                 formats.append({
215                     'quality': QUALITIES(fid),
216                     'format_id': fid,
217                     'url': furl,
218                 })
219             self._sort_formats(formats)
220             info = {
221                 'formats': formats,
222             }
223         else:  # request JSON file
224             if not document_id:
225                 video_id = self._search_regex(
226                     r'/play/(?:config|media)/(\d+)', webpage, 'media id')
227             info = self._extract_media_info(
228                 'http://www.ardmediathek.de/play/media/%s' % video_id,
229                 webpage, video_id)
230
231         info.update({
232             'id': video_id,
233             'title': self._live_title(title) if info.get('is_live') else title,
234             'description': description,
235             'thumbnail': thumbnail,
236         })
237
238         return info
239
240
241 class ARDIE(InfoExtractor):
242     _VALID_URL = r'(?P<mainurl>https?://(www\.)?daserste\.de/[^?#]+/videos/(?P<display_id>[^/?#]+)-(?P<id>[0-9]+))\.html'
243     _TESTS = [{
244         # available till 14.02.2019
245         'url': 'http://www.daserste.de/information/talk/maischberger/videos/das-groko-drama-zerlegen-sich-die-volksparteien-video-102.html',
246         'md5': '8e4ec85f31be7c7fc08a26cdbc5a1f49',
247         'info_dict': {
248             'display_id': 'das-groko-drama-zerlegen-sich-die-volksparteien-video',
249             'id': '102',
250             'ext': 'mp4',
251             'duration': 4435.0,
252             'title': 'Das GroKo-Drama: Zerlegen sich die Volksparteien?',
253             'upload_date': '20180214',
254             'thumbnail': r're:^https?://.*\.jpg$',
255         },
256     }, {
257         'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
258         'only_matching': True,
259     }]
260
261     def _real_extract(self, url):
262         mobj = re.match(self._VALID_URL, url)
263         display_id = mobj.group('display_id')
264
265         player_url = mobj.group('mainurl') + '~playerXml.xml'
266         doc = self._download_xml(player_url, display_id)
267         video_node = doc.find('./video')
268         upload_date = unified_strdate(xpath_text(
269             video_node, './broadcastDate'))
270         thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
271
272         formats = []
273         for a in video_node.findall('.//asset'):
274             f = {
275                 'format_id': a.attrib['type'],
276                 'width': int_or_none(a.find('./frameWidth').text),
277                 'height': int_or_none(a.find('./frameHeight').text),
278                 'vbr': int_or_none(a.find('./bitrateVideo').text),
279                 'abr': int_or_none(a.find('./bitrateAudio').text),
280                 'vcodec': a.find('./codecVideo').text,
281                 'tbr': int_or_none(a.find('./totalBitrate').text),
282             }
283             if a.find('./serverPrefix').text:
284                 f['url'] = a.find('./serverPrefix').text
285                 f['playpath'] = a.find('./fileName').text
286             else:
287                 f['url'] = a.find('./fileName').text
288             formats.append(f)
289         self._sort_formats(formats)
290
291         return {
292             'id': mobj.group('id'),
293             'formats': formats,
294             'display_id': display_id,
295             'title': video_node.find('./title').text,
296             'duration': parse_duration(video_node.find('./duration').text),
297             'upload_date': upload_date,
298             'thumbnail': thumbnail,
299         }
300
301
302 class ARDBetaMediathekIE(InfoExtractor):
303     _VALID_URL = r'https://(?:beta|www)\.ardmediathek\.de/[^/]+/(?:player|live)/(?P<video_id>[a-zA-Z0-9]+)(?:/(?P<display_id>[^/?#]+))?'
304     _TESTS = [{
305         'url': 'https://beta.ardmediathek.de/ard/player/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE/die-robuste-roswita',
306         'md5': '2d02d996156ea3c397cfc5036b5d7f8f',
307         'info_dict': {
308             'display_id': 'die-robuste-roswita',
309             'id': 'Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE',
310             'title': 'Tatort: Die robuste Roswita',
311             'description': r're:^Der Mord.*trüber ist als die Ilm.',
312             'duration': 5316,
313             'thumbnail': 'https://img.ardmediathek.de/standard/00/55/43/59/34/-1774185891/16x9/960?mandant=ard',
314             'upload_date': '20180826',
315             'ext': 'mp4',
316         },
317     }, {
318         'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3N3ci5kZS9hZXgvbzEwNzE5MTU/',
319         'only_matching': True,
320     }, {
321         'url': 'https://www.ardmediathek.de/swr/live/Y3JpZDovL3N3ci5kZS8xMzQ4MTA0Mg',
322         'only_matching': True,
323     }]
324
325     def _real_extract(self, url):
326         mobj = re.match(self._VALID_URL, url)
327         video_id = mobj.group('video_id')
328         display_id = mobj.group('display_id') or video_id
329
330         webpage = self._download_webpage(url, display_id)
331         data_json = self._search_regex(r'window\.__APOLLO_STATE__\s*=\s*(\{.*);\n', webpage, 'json')
332         data = self._parse_json(data_json, display_id)
333
334         res = {
335             'id': video_id,
336             'display_id': display_id,
337         }
338         formats = []
339         for widget in data.values():
340             if widget.get('_geoblocked'):
341                 raise ExtractorError('This video is not available due to geoblocking', expected=True)
342
343             if '_duration' in widget:
344                 res['duration'] = widget['_duration']
345             if 'clipTitle' in widget:
346                 res['title'] = widget['clipTitle']
347             if '_previewImage' in widget:
348                 res['thumbnail'] = widget['_previewImage']
349             if 'broadcastedOn' in widget:
350                 res['upload_date'] = unified_strdate(widget['broadcastedOn'])
351             if 'synopsis' in widget:
352                 res['description'] = widget['synopsis']
353             if '_subtitleUrl' in widget:
354                 res['subtitles'] = {'de': [{
355                     'ext': 'ttml',
356                     'url': widget['_subtitleUrl'],
357                 }]}
358             if '_quality' in widget:
359                 format_url = widget['_stream']['json'][0]
360
361                 if format_url.endswith('.f4m'):
362                     formats.extend(self._extract_f4m_formats(
363                         format_url + '?hdcore=3.11.0',
364                         video_id, f4m_id='hds', fatal=False))
365                 elif format_url.endswith('m3u8'):
366                     formats.extend(self._extract_m3u8_formats(
367                         format_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
368                 else:
369                     formats.append({
370                         'format_id': 'http-' + widget['_quality'],
371                         'url': format_url,
372                         'preference': 10,  # Plain HTTP, that's nice
373                     })
374
375         self._sort_formats(formats)
376         res['formats'] = formats
377
378         return res