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