[wdr] Rework extractors (closes #14598)
[youtube-dl] / youtube_dl / extractor / wdr.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_str,
9     compat_urlparse,
10 )
11 from ..utils import (
12     determine_ext,
13     ExtractorError,
14     js_to_json,
15     strip_jsonp,
16     try_get,
17     unified_strdate,
18     update_url_query,
19     urlhandle_detect_ext,
20 )
21
22
23 class WDRIE(InfoExtractor):
24     _VALID_URL = r'https?://deviceids-medp\.wdr\.de/ondemand/\d+/(?P<id>\d+)\.js'
25     _TEST = {
26         'url': 'http://deviceids-medp.wdr.de/ondemand/155/1557833.js',
27         'info_dict': {
28             'id': 'mdb-1140188',
29             'display_id': 'dfb-team-geht-gut-gelaunt-ins-spiel-gegen-polen-100',
30             'ext': 'mp4',
31             'title': 'DFB-Team geht gut gelaunt ins Spiel gegen Polen',
32             'description': 'Vor dem zweiten Gruppenspiel gegen Polen herrscht gute Stimmung im deutschen Team. Insbesondere Bastian Schweinsteiger strotzt vor Optimismus nach seinem Tor gegen die Ukraine.',
33             'upload_date': '20160615',
34         },
35         'skip': 'Geo-restricted to Germany',
36     }
37
38     def _real_extract(self, url):
39         video_id = self._match_id(url)
40
41         metadata = self._download_json(
42             url, video_id, transform_source=strip_jsonp)
43
44         is_live = metadata.get('mediaType') == 'live'
45
46         tracker_data = metadata['trackerData']
47         media_resource = metadata['mediaResource']
48
49         formats = []
50
51         # check if the metadata contains a direct URL to a file
52         for kind, media_resource in media_resource.items():
53             if kind not in ('dflt', 'alt'):
54                 continue
55
56             for tag_name, medium_url in media_resource.items():
57                 if tag_name not in ('videoURL', 'audioURL'):
58                     continue
59
60                 ext = determine_ext(medium_url)
61                 if ext == 'm3u8':
62                     formats.extend(self._extract_m3u8_formats(
63                         medium_url, video_id, 'mp4', 'm3u8_native',
64                         m3u8_id='hls'))
65                 elif ext == 'f4m':
66                     manifest_url = update_url_query(
67                         medium_url, {'hdcore': '3.2.0', 'plugin': 'aasp-3.2.0.77.18'})
68                     formats.extend(self._extract_f4m_formats(
69                         manifest_url, video_id, f4m_id='hds', fatal=False))
70                 elif ext == 'smil':
71                     formats.extend(self._extract_smil_formats(
72                         medium_url, 'stream', fatal=False))
73                 else:
74                     a_format = {
75                         'url': medium_url
76                     }
77                     if ext == 'unknown_video':
78                         urlh = self._request_webpage(
79                             medium_url, video_id, note='Determining extension')
80                         ext = urlhandle_detect_ext(urlh)
81                         a_format['ext'] = ext
82                     formats.append(a_format)
83
84         self._sort_formats(formats)
85
86         subtitles = {}
87         caption_url = media_resource.get('captionURL')
88         if caption_url:
89             subtitles['de'] = [{
90                 'url': caption_url,
91                 'ext': 'ttml',
92             }]
93
94         title = tracker_data['trackerClipTitle']
95
96         return {
97             'id': tracker_data.get('trackerClipId', video_id),
98             'title': self._live_title(title) if is_live else title,
99             'alt_title': tracker_data.get('trackerClipSubcategory'),
100             'formats': formats,
101             'subtitles': subtitles,
102             'upload_date': unified_strdate(tracker_data.get('trackerClipAirTime')),
103             'is_live': is_live,
104         }
105
106
107 class WDRPageIE(InfoExtractor):
108     _CURRENT_MAUS_URL = r'https?://(?:www\.)wdrmaus.de/(?:[^/]+/){1,2}[^/?#]+\.php5'
109     _PAGE_REGEX = r'/(?:mediathek/)?(?:[^/]+/)*(?P<display_id>[^/]+)\.html'
110     _VALID_URL = r'https?://(?:www\d?\.)?(?:wdr\d?|sportschau)\.de' + _PAGE_REGEX + '|' + _CURRENT_MAUS_URL
111
112     _TESTS = [
113         {
114             'url': 'http://www1.wdr.de/mediathek/video/sendungen/doku-am-freitag/video-geheimnis-aachener-dom-100.html',
115             # HDS download, MD5 is unstable
116             'info_dict': {
117                 'id': 'mdb-1058683',
118                 'ext': 'flv',
119                 'display_id': 'doku-am-freitag/video-geheimnis-aachener-dom-100',
120                 'title': 'Geheimnis Aachener Dom',
121                 'alt_title': 'Doku am Freitag',
122                 'upload_date': '20160304',
123                 'description': 'md5:87be8ff14d8dfd7a7ee46f0299b52318',
124                 'is_live': False,
125                 'subtitles': {'de': [{
126                     'url': 'http://ondemand-ww.wdr.de/medp/fsk0/105/1058683/1058683_12220974.xml',
127                     'ext': 'ttml',
128                 }]},
129             },
130             'skip': 'HTTP Error 404: Not Found',
131         },
132         {
133             'url': 'http://www1.wdr.de/mediathek/audio/wdr3/wdr3-gespraech-am-samstag/audio-schriftstellerin-juli-zeh-100.html',
134             'md5': 'f4c1f96d01cf285240f53ea4309663d8',
135             'info_dict': {
136                 'id': 'mdb-1072000',
137                 'ext': 'mp3',
138                 'display_id': 'wdr3-gespraech-am-samstag/audio-schriftstellerin-juli-zeh-100',
139                 'title': 'Schriftstellerin Juli Zeh',
140                 'alt_title': 'WDR 3 Gespräch am Samstag',
141                 'upload_date': '20160312',
142                 'description': 'md5:e127d320bc2b1f149be697ce044a3dd7',
143                 'is_live': False,
144                 'subtitles': {}
145             },
146             'skip': 'HTTP Error 404: Not Found',
147         },
148         {
149             'url': 'http://www1.wdr.de/mediathek/video/live/index.html',
150             'info_dict': {
151                 'id': 'mdb-1406149',
152                 'ext': 'mp4',
153                 'title': r're:^WDR Fernsehen im Livestream \(nur in Deutschland erreichbar\) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
154                 'alt_title': 'WDR Fernsehen Live',
155                 'upload_date': '20150101',
156                 'is_live': True,
157             },
158             'params': {
159                 'skip_download': True,  # m3u8 download
160             },
161         },
162         {
163             'url': 'http://www1.wdr.de/mediathek/video/sendungen/aktuelle-stunde/aktuelle-stunde-120.html',
164             'playlist_mincount': 7,
165             'info_dict': {
166                 'id': 'aktuelle-stunde-120',
167             },
168         },
169         {
170             'url': 'http://www.wdrmaus.de/aktuelle-sendung/index.php5',
171             'info_dict': {
172                 'id': 'mdb-1552552',
173                 'ext': 'mp4',
174                 'upload_date': 're:^[0-9]{8}$',
175                 'title': 're:^Die Sendung mit der Maus vom [0-9.]{10}$',
176             },
177             'skip': 'The id changes from week to week because of the new episode'
178         },
179         {
180             'url': 'http://www.wdrmaus.de/filme/sachgeschichten/achterbahn.php5',
181             'md5': '803138901f6368ee497b4d195bb164f2',
182             'info_dict': {
183                 'id': 'mdb-186083',
184                 'ext': 'mp4',
185                 'upload_date': '20130919',
186                 'title': 'Sachgeschichte - Achterbahn ',
187             },
188         },
189         {
190             'url': 'http://www1.wdr.de/radio/player/radioplayer116~_layout-popupVersion.html',
191             # Live stream, MD5 unstable
192             'info_dict': {
193                 'id': 'mdb-869971',
194                 'ext': 'mp4',
195                 'title': r're:^COSMO Livestream [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
196                 'upload_date': '20160101',
197             },
198             'params': {
199                 'skip_download': True,  # m3u8 download
200             }
201         },
202         {
203             'url': 'http://www.sportschau.de/handballem2018/handball-nationalmannschaft-em-stolperstein-vorrunde-100.html',
204             'info_dict': {
205                 'id': 'mdb-1556012',
206                 'ext': 'mp4',
207                 'title': 'DHB-Vizepräsident Bob Hanning - "Die Weltspitze ist extrem breit"',
208                 'upload_date': '20180111',
209             },
210             'params': {
211                 'skip_download': True,
212             },
213         },
214         {
215             'url': 'http://www.sportschau.de/handballem2018/audio-vorschau---die-handball-em-startet-mit-grossem-favoritenfeld-100.html',
216             'only_matching': True,
217         }
218     ]
219
220     def _real_extract(self, url):
221         mobj = re.match(self._VALID_URL, url)
222         display_id = mobj.group('display_id')
223         webpage = self._download_webpage(url, display_id)
224
225         entries = []
226
227         # Article with several videos
228
229         # for wdr.de the data-extension is in a tag with the class "mediaLink"
230         # for wdr.de radio players, in a tag with the class "wdrrPlayerPlayBtn"
231         # for wdrmaus, in a tag with the class "videoButton" (previously a link
232         # to the page in a multiline "videoLink"-tag)
233         for mobj in re.finditer(
234             r'''(?sx)class=
235                     (?:
236                         (["\'])(?:mediaLink|wdrrPlayerPlayBtn|videoButton)\b.*?\1[^>]+|
237                         (["\'])videoLink\b.*?\2[\s]*>\n[^\n]*
238                     )data-extension=(["\'])(?P<data>(?:(?!\3).)+)\3
239                     ''', webpage):
240             media_link_obj = self._parse_json(
241                 mobj.group('data'), display_id, transform_source=js_to_json,
242                 fatal=False)
243             if not media_link_obj:
244                 continue
245             jsonp_url = try_get(
246                 media_link_obj, lambda x: x['mediaObj']['url'], compat_str)
247             if jsonp_url:
248                 entries.append(self.url_result(jsonp_url, ie=WDRIE.ie_key()))
249
250         # Playlist (e.g. https://www1.wdr.de/mediathek/video/sendungen/aktuelle-stunde/aktuelle-stunde-120.html)
251         if not entries:
252             entries = [
253                 self.url_result(
254                     compat_urlparse.urljoin(url, mobj.group('href')),
255                     ie=WDRPageIE.ie_key())
256                 for mobj in re.finditer(
257                     r'<a[^>]+\bhref=(["\'])(?P<href>(?:(?!\1).)+)\1[^>]+\bdata-extension=',
258                     webpage) if re.match(self._PAGE_REGEX, mobj.group('href'))
259             ]
260
261         return self.playlist_result(entries, playlist_id=display_id)
262
263
264 class WDRElefantIE(InfoExtractor):
265     _VALID_URL = r'https?://(?:www\.)wdrmaus\.de/elefantenseite/#(?P<id>.+)'
266     _TEST = {
267         'url': 'http://www.wdrmaus.de/elefantenseite/#folge_ostern_2015',
268         'info_dict': {
269             'title': 'Folge Oster-Spezial 2015',
270             'id': 'mdb-1088195',
271             'ext': 'mp4',
272             'age_limit': None,
273             'upload_date': '20150406'
274         },
275         'params': {
276             'skip_download': True,
277         },
278     }
279
280     def _real_extract(self, url):
281         display_id = self._match_id(url)
282
283         # Table of Contents seems to always be at this address, so fetch it directly.
284         # The website fetches configurationJS.php5, which links to tableOfContentsJS.php5.
285         table_of_contents = self._download_json(
286             'https://www.wdrmaus.de/elefantenseite/data/tableOfContentsJS.php5',
287             display_id)
288         if display_id not in table_of_contents:
289             raise ExtractorError(
290                 'No entry in site\'s table of contents for this URL. '
291                 'Is the fragment part of the URL (after the #) correct?',
292                 expected=True)
293         xml_metadata_path = table_of_contents[display_id]['xmlPath']
294         xml_metadata = self._download_xml(
295             'https://www.wdrmaus.de/elefantenseite/' + xml_metadata_path,
296             display_id)
297         zmdb_url_element = xml_metadata.find('./movie/zmdb_url')
298         if zmdb_url_element is None:
299             raise ExtractorError(
300                 '%s is not a video' % display_id, expected=True)
301         return self.url_result(zmdb_url_element.text, ie=WDRIE.ie_key())
302
303
304 class WDRMobileIE(InfoExtractor):
305     _VALID_URL = r'''(?x)
306         https?://mobile-ondemand\.wdr\.de/
307         .*?/fsk(?P<age_limit>[0-9]+)
308         /[0-9]+/[0-9]+/
309         (?P<id>[0-9]+)_(?P<title>[0-9]+)'''
310     IE_NAME = 'wdr:mobile'
311     _TEST = {
312         'url': 'http://mobile-ondemand.wdr.de/CMS2010/mdb/ondemand/weltweit/fsk0/42/421735/421735_4283021.mp4',
313         'info_dict': {
314             'title': '4283021',
315             'id': '421735',
316             'ext': 'mp4',
317             'age_limit': 0,
318         },
319         'skip': 'Problems with loading data.'
320     }
321
322     def _real_extract(self, url):
323         mobj = re.match(self._VALID_URL, url)
324         return {
325             'id': mobj.group('id'),
326             'title': mobj.group('title'),
327             'age_limit': int(mobj.group('age_limit')),
328             'url': url,
329             'http_headers': {
330                 'User-Agent': 'mobile',
331             },
332         }