1# coding: utf-8
2from __future__ import unicode_literals
3
4from .common import InfoExtractor
5from ..utils import (
6    determine_ext,
7    int_or_none,
8    parse_duration,
9    qualities,
10    try_get,
11    unified_strdate,
12    urljoin,
13)
14
15
16class NDRBaseIE(InfoExtractor):
17    def _real_extract(self, url):
18        mobj = self._match_valid_url(url)
19        display_id = next(group for group in mobj.groups() if group)
20        id = mobj.group('id')
21        webpage = self._download_webpage(url, display_id)
22        return self._extract_embed(webpage, display_id, id)
23
24
25class NDRIE(NDRBaseIE):
26    IE_NAME = 'ndr'
27    IE_DESC = 'NDR.de - Norddeutscher Rundfunk'
28    _VALID_URL = r'https?://(?:www\.)?(?:daserste\.)?ndr\.de/(?:[^/]+/)*(?P<display_id>[^/?#]+),(?P<id>[\da-z]+)\.html'
29    _TESTS = [{
30        'url': 'http://www.ndr.de/fernsehen/Party-Poette-und-Parade,hafengeburtstag988.html',
31        'info_dict': {
32            'id': 'hafengeburtstag988',
33            'ext': 'mp4',
34            'title': 'Party, Pötte und Parade',
35            'thumbnail': 'https://www.ndr.de/fernsehen/hafengeburtstag990_v-contentxl.jpg',
36            'description': 'md5:ad14f9d2f91d3040b6930c697e5f6b4c',
37            'series': None,
38            'channel': 'NDR Fernsehen',
39            'upload_date': '20150508',
40            'duration': 3498,
41        },
42    }, {
43        'url': 'https://www.ndr.de/sport/fussball/Rostocks-Matchwinner-Froede-Ein-Hansa-Debuet-wie-im-Maerchen,hansa10312.html',
44        'only_matching': True
45    }, {
46        'url': 'https://www.ndr.de/nachrichten/niedersachsen/kommunalwahl_niedersachsen_2021/Grosse-Parteien-zufrieden-mit-Ergebnissen-der-Kommunalwahl,kommunalwahl1296.html',
47        'info_dict': {
48            'id': 'kommunalwahl1296',
49            'ext': 'mp4',
50            'title': 'Die Spitzenrunde: Die Wahl aus Sicht der Landespolitik',
51            'thumbnail': 'https://www.ndr.de/fernsehen/screenshot1194912_v-contentxl.jpg',
52            'description': 'md5:5c6e2ad744cef499135735a1036d7aa7',
53            'series': 'Hallo Niedersachsen',
54            'channel': 'NDR Fernsehen',
55            'upload_date': '20210913',
56            'duration': 438,
57        },
58    }, {
59        'url': 'https://www.ndr.de/fernsehen/sendungen/extra_3/extra-3-Satiremagazin-mit-Christian-Ehring,sendung1091858.html',
60        'info_dict': {
61            'id': 'sendung1091858',
62            'ext': 'mp4',
63            'title': 'Extra 3 vom 11.11.2020 mit Christian Ehring',
64            'thumbnail': 'https://www.ndr.de/fernsehen/screenshot983938_v-contentxl.jpg',
65            'description': 'md5:700f6de264010585012a72f97b0ac0c9',
66            'series': 'extra 3',
67            'channel': 'NDR Fernsehen',
68            'upload_date': '20201111',
69            'duration': 1749,
70        }
71    }, {
72        'url': 'http://www.ndr.de/info/La-Valette-entgeht-der-Hinrichtung,audio51535.html',
73        'info_dict': {
74            'id': 'audio51535',
75            'ext': 'mp3',
76            'title': 'La Valette entgeht der Hinrichtung',
77            'thumbnail': 'https://www.ndr.de/mediathek/mediathekbild140_v-podcast.jpg',
78            'description': 'md5:22f9541913a40fe50091d5cdd7c9f536',
79            'upload_date': '20140729',
80            'duration': 884.0,
81        },
82        'expected_warnings': ['unable to extract json url'],
83    }]
84
85    def _extract_embed(self, webpage, display_id, id):
86        formats = []
87        base_url = 'https://www.ndr.de'
88        json_url = self._search_regex(r'<iframe[^>]+src=\"([^\"]+)_theme-ndrde[^\.]*\.html\"', webpage,
89                                      'json url', fatal=False)
90        if json_url:
91            data_json = self._download_json(base_url + json_url.replace('ardplayer_image', 'ardjson_image') + '.json',
92                                            id, fatal=False)
93            info_json = data_json.get('_info', {})
94            media_json = try_get(data_json, lambda x: x['_mediaArray'][0]['_mediaStreamArray'])
95            for media in media_json:
96                if media.get('_quality') == 'auto':
97                    formats.extend(self._extract_m3u8_formats(media['_stream'], id))
98            subtitles = {}
99            sub_url = data_json.get('_subtitleUrl')
100            if sub_url:
101                subtitles.setdefault('de', []).append({
102                    'url': base_url + sub_url,
103                })
104            self._sort_formats(formats)
105            return {
106                'id': id,
107                'title': info_json.get('clipTitle'),
108                'thumbnail': base_url + data_json.get('_previewImage'),
109                'description': info_json.get('clipDescription'),
110                'series': info_json.get('seriesTitle') or None,
111                'channel': info_json.get('channelTitle'),
112                'upload_date': unified_strdate(info_json.get('clipDate')),
113                'duration': data_json.get('_duration'),
114                'formats': formats,
115                'subtitles': subtitles,
116            }
117        else:
118            json_url = base_url + self._search_regex(r'apiUrl\s?=\s?\'([^\']+)\'', webpage, 'json url').replace(
119                '_belongsToPodcast-', '')
120            data_json = self._download_json(json_url, id, fatal=False)
121            return {
122                'id': id,
123                'title': data_json.get('title'),
124                'thumbnail': base_url + data_json.get('poster'),
125                'description': data_json.get('summary'),
126                'upload_date': unified_strdate(data_json.get('publicationDate')),
127                'duration': parse_duration(data_json.get('duration')),
128                'formats': [{
129                    'url': try_get(data_json, (lambda x: x['audio'][0]['url'], lambda x: x['files'][0]['url'])),
130                    'vcodec': 'none',
131                    'ext': 'mp3',
132                }],
133            }
134
135
136class NJoyIE(NDRBaseIE):
137    IE_NAME = 'njoy'
138    IE_DESC = 'N-JOY'
139    _VALID_URL = r'https?://(?:www\.)?n-joy\.de/(?:[^/]+/)*(?:(?P<display_id>[^/?#]+),)?(?P<id>[\da-z]+)\.html'
140    _TESTS = [{
141        # httpVideo, same content id
142        'url': 'http://www.n-joy.de/entertainment/comedy/comedy_contest/Benaissa-beim-NDR-Comedy-Contest,comedycontest2480.html',
143        'md5': 'cb63be60cd6f9dd75218803146d8dc67',
144        'info_dict': {
145            'id': 'comedycontest2480',
146            'display_id': 'Benaissa-beim-NDR-Comedy-Contest',
147            'ext': 'mp4',
148            'title': 'Benaissa beim NDR Comedy Contest',
149            'description': 'md5:f057a6c4e1c728b10d33b5ffd36ddc39',
150            'uploader': 'ndrtv',
151            'upload_date': '20141129',
152            'duration': 654,
153        },
154        'params': {
155            'skip_download': True,
156        },
157    }, {
158        # httpVideo, different content id
159        'url': 'http://www.n-joy.de/musik/Das-frueheste-DJ-Set-des-Nordens-live-mit-Felix-Jaehn-,felixjaehn168.html',
160        'md5': '417660fffa90e6df2fda19f1b40a64d8',
161        'info_dict': {
162            'id': 'dockville882',
163            'display_id': 'Das-frueheste-DJ-Set-des-Nordens-live-mit-Felix-Jaehn-',
164            'ext': 'mp4',
165            'title': '"Ich hab noch nie" mit Felix Jaehn',
166            'description': 'md5:85dd312d53be1b99e1f998a16452a2f3',
167            'uploader': 'njoy',
168            'upload_date': '20150822',
169            'duration': 211,
170        },
171        'params': {
172            'skip_download': True,
173        },
174    }, {
175        'url': 'http://www.n-joy.de/radio/webradio/morningshow209.html',
176        'only_matching': True,
177    }]
178
179    def _extract_embed(self, webpage, display_id, id):
180        video_id = self._search_regex(
181            r'<iframe[^>]+id="pp_([\da-z]+)"', webpage, 'embed id')
182        description = self._search_regex(
183            r'<div[^>]+class="subline"[^>]*>[^<]+</div>\s*<p>([^<]+)</p>',
184            webpage, 'description', fatal=False)
185        return {
186            '_type': 'url_transparent',
187            'ie_key': 'NDREmbedBase',
188            'url': 'ndr:%s' % video_id,
189            'display_id': display_id,
190            'description': description,
191        }
192
193
194class NDREmbedBaseIE(InfoExtractor):
195    IE_NAME = 'ndr:embed:base'
196    _VALID_URL = r'(?:ndr:(?P<id_s>[\da-z]+)|https?://www\.ndr\.de/(?P<id>[\da-z]+)-ppjson\.json)'
197    _TESTS = [{
198        'url': 'ndr:soundcheck3366',
199        'only_matching': True,
200    }, {
201        'url': 'http://www.ndr.de/soundcheck3366-ppjson.json',
202        'only_matching': True,
203    }]
204
205    def _real_extract(self, url):
206        mobj = self._match_valid_url(url)
207        video_id = mobj.group('id') or mobj.group('id_s')
208
209        ppjson = self._download_json(
210            'http://www.ndr.de/%s-ppjson.json' % video_id, video_id)
211
212        playlist = ppjson['playlist']
213
214        formats = []
215        quality_key = qualities(('xs', 's', 'm', 'l', 'xl'))
216
217        for format_id, f in playlist.items():
218            src = f.get('src')
219            if not src:
220                continue
221            ext = determine_ext(src, None)
222            if ext == 'f4m':
223                formats.extend(self._extract_f4m_formats(
224                    src + '?hdcore=3.7.0&plugin=aasp-3.7.0.39.44', video_id,
225                    f4m_id='hds', fatal=False))
226            elif ext == 'm3u8':
227                formats.extend(self._extract_m3u8_formats(
228                    src, video_id, 'mp4', m3u8_id='hls',
229                    entry_protocol='m3u8_native', fatal=False))
230            else:
231                quality = f.get('quality')
232                ff = {
233                    'url': src,
234                    'format_id': quality or format_id,
235                    'quality': quality_key(quality),
236                }
237                type_ = f.get('type')
238                if type_ and type_.split('/')[0] == 'audio':
239                    ff['vcodec'] = 'none'
240                    ff['ext'] = ext or 'mp3'
241                formats.append(ff)
242        self._sort_formats(formats)
243
244        config = playlist['config']
245
246        live = playlist.get('config', {}).get('streamType') in ['httpVideoLive', 'httpAudioLive']
247        title = config['title']
248        uploader = ppjson.get('config', {}).get('branding')
249        upload_date = ppjson.get('config', {}).get('publicationDate')
250        duration = int_or_none(config.get('duration'))
251
252        thumbnails = []
253        poster = try_get(config, lambda x: x['poster'], dict) or {}
254        for thumbnail_id, thumbnail in poster.items():
255            thumbnail_url = urljoin(url, thumbnail.get('src'))
256            if not thumbnail_url:
257                continue
258            thumbnails.append({
259                'id': thumbnail.get('quality') or thumbnail_id,
260                'url': thumbnail_url,
261                'preference': quality_key(thumbnail.get('quality')),
262            })
263
264        subtitles = {}
265        tracks = config.get('tracks')
266        if tracks and isinstance(tracks, list):
267            for track in tracks:
268                if not isinstance(track, dict):
269                    continue
270                track_url = urljoin(url, track.get('src'))
271                if not track_url:
272                    continue
273                subtitles.setdefault(track.get('srclang') or 'de', []).append({
274                    'url': track_url,
275                    'ext': 'ttml',
276                })
277
278        return {
279            'id': video_id,
280            'title': title,
281            'is_live': live,
282            'uploader': uploader if uploader != '-' else None,
283            'upload_date': upload_date[0:8] if upload_date else None,
284            'duration': duration,
285            'thumbnails': thumbnails,
286            'formats': formats,
287            'subtitles': subtitles,
288        }
289
290
291class NDREmbedIE(NDREmbedBaseIE):
292    IE_NAME = 'ndr:embed'
293    _VALID_URL = r'https?://(?:www\.)?(?:daserste\.)?ndr\.de/(?:[^/]+/)*(?P<id>[\da-z]+)-(?:player|externalPlayer)\.html'
294    _TESTS = [{
295        'url': 'http://www.ndr.de/fernsehen/sendungen/ndr_aktuell/ndraktuell28488-player.html',
296        'md5': '8b9306142fe65bbdefb5ce24edb6b0a9',
297        'info_dict': {
298            'id': 'ndraktuell28488',
299            'ext': 'mp4',
300            'title': 'Norddeutschland begrüßt Flüchtlinge',
301            'is_live': False,
302            'uploader': 'ndrtv',
303            'upload_date': '20150907',
304            'duration': 132,
305        },
306    }, {
307        'url': 'http://www.ndr.de/ndr2/events/soundcheck/soundcheck3366-player.html',
308        'md5': '002085c44bae38802d94ae5802a36e78',
309        'info_dict': {
310            'id': 'soundcheck3366',
311            'ext': 'mp4',
312            'title': 'Ella Henderson braucht Vergleiche nicht zu scheuen',
313            'is_live': False,
314            'uploader': 'ndr2',
315            'upload_date': '20150912',
316            'duration': 3554,
317        },
318        'params': {
319            'skip_download': True,
320        },
321    }, {
322        'url': 'http://www.ndr.de/info/audio51535-player.html',
323        'md5': 'bb3cd38e24fbcc866d13b50ca59307b8',
324        'info_dict': {
325            'id': 'audio51535',
326            'ext': 'mp3',
327            'title': 'La Valette entgeht der Hinrichtung',
328            'is_live': False,
329            'uploader': 'ndrinfo',
330            'upload_date': '20140729',
331            'duration': 884,
332        },
333        'params': {
334            'skip_download': True,
335        },
336    }, {
337        'url': 'http://www.ndr.de/fernsehen/sendungen/visite/visite11010-externalPlayer.html',
338        'md5': 'ae57f80511c1e1f2fd0d0d3d31aeae7c',
339        'info_dict': {
340            'id': 'visite11010',
341            'ext': 'mp4',
342            'title': 'Visite - die ganze Sendung',
343            'is_live': False,
344            'uploader': 'ndrtv',
345            'upload_date': '20150902',
346            'duration': 3525,
347        },
348        'params': {
349            'skip_download': True,
350        },
351    }, {
352        # httpVideoLive
353        'url': 'http://www.ndr.de/fernsehen/livestream/livestream217-externalPlayer.html',
354        'info_dict': {
355            'id': 'livestream217',
356            'ext': 'flv',
357            'title': r're:^NDR Fernsehen Niedersachsen \d{4}-\d{2}-\d{2} \d{2}:\d{2}$',
358            'is_live': True,
359            'upload_date': '20150910',
360        },
361        'params': {
362            'skip_download': True,
363        },
364    }, {
365        'url': 'http://www.ndr.de/ndrkultur/audio255020-player.html',
366        'only_matching': True,
367    }, {
368        'url': 'http://www.ndr.de/fernsehen/sendungen/nordtour/nordtour7124-player.html',
369        'only_matching': True,
370    }, {
371        'url': 'http://www.ndr.de/kultur/film/videos/videoimport10424-player.html',
372        'only_matching': True,
373    }, {
374        'url': 'http://www.ndr.de/fernsehen/sendungen/hamburg_journal/hamj43006-player.html',
375        'only_matching': True,
376    }, {
377        'url': 'http://www.ndr.de/fernsehen/sendungen/weltbilder/weltbilder4518-player.html',
378        'only_matching': True,
379    }, {
380        'url': 'http://www.ndr.de/fernsehen/doku952-player.html',
381        'only_matching': True,
382    }]
383
384
385class NJoyEmbedIE(NDREmbedBaseIE):
386    IE_NAME = 'njoy:embed'
387    _VALID_URL = r'https?://(?:www\.)?n-joy\.de/(?:[^/]+/)*(?P<id>[\da-z]+)-(?:player|externalPlayer)_[^/]+\.html'
388    _TESTS = [{
389        # httpVideo
390        'url': 'http://www.n-joy.de/events/reeperbahnfestival/doku948-player_image-bc168e87-5263-4d6d-bd27-bb643005a6de_theme-n-joy.html',
391        'md5': '8483cbfe2320bd4d28a349d62d88bd74',
392        'info_dict': {
393            'id': 'doku948',
394            'ext': 'mp4',
395            'title': 'Zehn Jahre Reeperbahn Festival - die Doku',
396            'is_live': False,
397            'upload_date': '20150807',
398            'duration': 1011,
399        },
400    }, {
401        # httpAudio
402        'url': 'http://www.n-joy.de/news_wissen/stefanrichter100-player_image-d5e938b1-f21a-4b9a-86b8-aaba8bca3a13_theme-n-joy.html',
403        'md5': 'd989f80f28ac954430f7b8a48197188a',
404        'info_dict': {
405            'id': 'stefanrichter100',
406            'ext': 'mp3',
407            'title': 'Interview mit einem Augenzeugen',
408            'is_live': False,
409            'uploader': 'njoy',
410            'upload_date': '20150909',
411            'duration': 140,
412        },
413        'params': {
414            'skip_download': True,
415        },
416    }, {
417        # httpAudioLive, no explicit ext
418        'url': 'http://www.n-joy.de/news_wissen/webradioweltweit100-player_image-3fec0484-2244-4565-8fb8-ed25fd28b173_theme-n-joy.html',
419        'info_dict': {
420            'id': 'webradioweltweit100',
421            'ext': 'mp3',
422            'title': r're:^N-JOY Weltweit \d{4}-\d{2}-\d{2} \d{2}:\d{2}$',
423            'is_live': True,
424            'uploader': 'njoy',
425            'upload_date': '20150810',
426        },
427        'params': {
428            'skip_download': True,
429        },
430    }, {
431        'url': 'http://www.n-joy.de/musik/dockville882-player_image-3905259e-0803-4764-ac72-8b7de077d80a_theme-n-joy.html',
432        'only_matching': True,
433    }, {
434        'url': 'http://www.n-joy.de/radio/sendungen/morningshow/urlaubsfotos190-player_image-066a5df1-5c95-49ec-a323-941d848718db_theme-n-joy.html',
435        'only_matching': True,
436    }, {
437        'url': 'http://www.n-joy.de/entertainment/comedy/krudetv290-player_image-ab261bfe-51bf-4bf3-87ba-c5122ee35b3d_theme-n-joy.html',
438        'only_matching': True,
439    }]
440