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