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