[youtube] Quick extraction tempfix (closes #22367, closes #22163)
[youtube-dl] / youtube_dl / extractor / prosiebensat1.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from hashlib import sha1
7 from .common import InfoExtractor
8 from ..compat import compat_str
9 from ..utils import (
10     ExtractorError,
11     determine_ext,
12     float_or_none,
13     int_or_none,
14     unified_strdate,
15 )
16
17
18 class ProSiebenSat1BaseIE(InfoExtractor):
19     _GEO_COUNTRIES = ['DE']
20     _ACCESS_ID = None
21     _SUPPORTED_PROTOCOLS = 'dash:clear,hls:clear,progressive:clear'
22     _V4_BASE_URL = 'https://vas-v4.p7s1video.net/4.0/get'
23
24     def _extract_video_info(self, url, clip_id):
25         client_location = url
26
27         video = self._download_json(
28             'http://vas.sim-technik.de/vas/live/v2/videos',
29             clip_id, 'Downloading videos JSON', query={
30                 'access_token': self._TOKEN,
31                 'client_location': client_location,
32                 'client_name': self._CLIENT_NAME,
33                 'ids': clip_id,
34             })[0]
35
36         if video.get('is_protected') is True:
37             raise ExtractorError('This video is DRM protected.', expected=True)
38
39         formats = []
40         if self._ACCESS_ID:
41             raw_ct = self._ENCRYPTION_KEY + clip_id + self._IV + self._ACCESS_ID
42             server_token = (self._download_json(
43                 self._V4_BASE_URL + 'protocols', clip_id,
44                 'Downloading protocols JSON',
45                 headers=self.geo_verification_headers(), query={
46                     'access_id': self._ACCESS_ID,
47                     'client_token': sha1((raw_ct).encode()).hexdigest(),
48                     'video_id': clip_id,
49                 }, fatal=False) or {}).get('server_token')
50             if server_token:
51                 urls = (self._download_json(
52                     self._V4_BASE_URL + 'urls', clip_id, 'Downloading urls JSON', query={
53                         'access_id': self._ACCESS_ID,
54                         'client_token': sha1((raw_ct + server_token + self._SUPPORTED_PROTOCOLS).encode()).hexdigest(),
55                         'protocols': self._SUPPORTED_PROTOCOLS,
56                         'server_token': server_token,
57                         'video_id': clip_id,
58                     }, fatal=False) or {}).get('urls') or {}
59                 for protocol, variant in urls.items():
60                     source_url = variant.get('clear', {}).get('url')
61                     if not source_url:
62                         continue
63                     if protocol == 'dash':
64                         formats.extend(self._extract_mpd_formats(
65                             source_url, clip_id, mpd_id=protocol, fatal=False))
66                     elif protocol == 'hls':
67                         formats.extend(self._extract_m3u8_formats(
68                             source_url, clip_id, 'mp4', 'm3u8_native',
69                             m3u8_id=protocol, fatal=False))
70                     else:
71                         formats.append({
72                             'url': source_url,
73                             'format_id': protocol,
74                         })
75         if not formats:
76             source_ids = [compat_str(source['id']) for source in video['sources']]
77
78             client_id = self._SALT[:2] + sha1(''.join([clip_id, self._SALT, self._TOKEN, client_location, self._SALT, self._CLIENT_NAME]).encode('utf-8')).hexdigest()
79
80             sources = self._download_json(
81                 'http://vas.sim-technik.de/vas/live/v2/videos/%s/sources' % clip_id,
82                 clip_id, 'Downloading sources JSON', query={
83                     'access_token': self._TOKEN,
84                     'client_id': client_id,
85                     'client_location': client_location,
86                     'client_name': self._CLIENT_NAME,
87                 })
88             server_id = sources['server_id']
89
90             def fix_bitrate(bitrate):
91                 bitrate = int_or_none(bitrate)
92                 if not bitrate:
93                     return None
94                 return (bitrate // 1000) if bitrate % 1000 == 0 else bitrate
95
96             for source_id in source_ids:
97                 client_id = self._SALT[:2] + sha1(''.join([self._SALT, clip_id, self._TOKEN, server_id, client_location, source_id, self._SALT, self._CLIENT_NAME]).encode('utf-8')).hexdigest()
98                 urls = self._download_json(
99                     'http://vas.sim-technik.de/vas/live/v2/videos/%s/sources/url' % clip_id,
100                     clip_id, 'Downloading urls JSON', fatal=False, query={
101                         'access_token': self._TOKEN,
102                         'client_id': client_id,
103                         'client_location': client_location,
104                         'client_name': self._CLIENT_NAME,
105                         'server_id': server_id,
106                         'source_ids': source_id,
107                     })
108                 if not urls:
109                     continue
110                 if urls.get('status_code') != 0:
111                     raise ExtractorError('This video is unavailable', expected=True)
112                 urls_sources = urls['sources']
113                 if isinstance(urls_sources, dict):
114                     urls_sources = urls_sources.values()
115                 for source in urls_sources:
116                     source_url = source.get('url')
117                     if not source_url:
118                         continue
119                     protocol = source.get('protocol')
120                     mimetype = source.get('mimetype')
121                     if mimetype == 'application/f4m+xml' or 'f4mgenerator' in source_url or determine_ext(source_url) == 'f4m':
122                         formats.extend(self._extract_f4m_formats(
123                             source_url, clip_id, f4m_id='hds', fatal=False))
124                     elif mimetype == 'application/x-mpegURL':
125                         formats.extend(self._extract_m3u8_formats(
126                             source_url, clip_id, 'mp4', 'm3u8_native',
127                             m3u8_id='hls', fatal=False))
128                     elif mimetype == 'application/dash+xml':
129                         formats.extend(self._extract_mpd_formats(
130                             source_url, clip_id, mpd_id='dash', fatal=False))
131                     else:
132                         tbr = fix_bitrate(source['bitrate'])
133                         if protocol in ('rtmp', 'rtmpe'):
134                             mobj = re.search(r'^(?P<url>rtmpe?://[^/]+)/(?P<path>.+)$', source_url)
135                             if not mobj:
136                                 continue
137                             path = mobj.group('path')
138                             mp4colon_index = path.rfind('mp4:')
139                             app = path[:mp4colon_index]
140                             play_path = path[mp4colon_index:]
141                             formats.append({
142                                 'url': '%s/%s' % (mobj.group('url'), app),
143                                 'app': app,
144                                 'play_path': play_path,
145                                 'player_url': 'http://livepassdl.conviva.com/hf/ver/2.79.0.17083/LivePassModuleMain.swf',
146                                 'page_url': 'http://www.prosieben.de',
147                                 'tbr': tbr,
148                                 'ext': 'flv',
149                                 'format_id': 'rtmp%s' % ('-%d' % tbr if tbr else ''),
150                             })
151                         else:
152                             formats.append({
153                                 'url': source_url,
154                                 'tbr': tbr,
155                                 'format_id': 'http%s' % ('-%d' % tbr if tbr else ''),
156                             })
157         self._sort_formats(formats)
158
159         return {
160             'duration': float_or_none(video.get('duration')),
161             'formats': formats,
162         }
163
164
165 class ProSiebenSat1IE(ProSiebenSat1BaseIE):
166     IE_NAME = 'prosiebensat1'
167     IE_DESC = 'ProSiebenSat.1 Digital'
168     _VALID_URL = r'''(?x)
169                     https?://
170                         (?:www\.)?
171                         (?:
172                             (?:beta\.)?
173                             (?:
174                                 prosieben(?:maxx)?|sixx|sat1(?:gold)?|kabeleins(?:doku)?|the-voice-of-germany|7tv|advopedia
175                             )\.(?:de|at|ch)|
176                             ran\.de|fem\.com|advopedia\.de|galileo\.tv/video
177                         )
178                         /(?P<id>.+)
179                     '''
180
181     _TESTS = [
182         {
183             # Tests changes introduced in https://github.com/ytdl-org/youtube-dl/pull/6242
184             # in response to fixing https://github.com/ytdl-org/youtube-dl/issues/6215:
185             # - malformed f4m manifest support
186             # - proper handling of URLs starting with `https?://` in 2.0 manifests
187             # - recursive child f4m manifests extraction
188             'url': 'http://www.prosieben.de/tv/circus-halligalli/videos/218-staffel-2-episode-18-jahresrueckblick-ganze-folge',
189             'info_dict': {
190                 'id': '2104602',
191                 'ext': 'mp4',
192                 'title': 'Episode 18 - Staffel 2',
193                 'description': 'md5:8733c81b702ea472e069bc48bb658fc1',
194                 'upload_date': '20131231',
195                 'duration': 5845.04,
196             },
197         },
198         {
199             'url': 'http://www.prosieben.de/videokatalog/Gesellschaft/Leben/Trends/video-Lady-Umstyling-f%C3%BCr-Audrina-Rebekka-Audrina-Fergen-billig-aussehen-Battal-Modica-700544.html',
200             'info_dict': {
201                 'id': '2570327',
202                 'ext': 'mp4',
203                 'title': 'Lady-Umstyling für Audrina',
204                 'description': 'md5:4c16d0c17a3461a0d43ea4084e96319d',
205                 'upload_date': '20131014',
206                 'duration': 606.76,
207             },
208             'params': {
209                 # rtmp download
210                 'skip_download': True,
211             },
212             'skip': 'Seems to be broken',
213         },
214         {
215             'url': 'http://www.prosiebenmaxx.de/tv/experience/video/144-countdown-fuer-die-autowerkstatt-ganze-folge',
216             'info_dict': {
217                 'id': '2429369',
218                 'ext': 'mp4',
219                 'title': 'Countdown für die Autowerkstatt',
220                 'description': 'md5:809fc051a457b5d8666013bc40698817',
221                 'upload_date': '20140223',
222                 'duration': 2595.04,
223             },
224             'params': {
225                 # rtmp download
226                 'skip_download': True,
227             },
228             'skip': 'This video is unavailable',
229         },
230         {
231             'url': 'http://www.sixx.de/stars-style/video/sexy-laufen-in-ugg-boots-clip',
232             'info_dict': {
233                 'id': '2904997',
234                 'ext': 'mp4',
235                 'title': 'Sexy laufen in Ugg Boots',
236                 'description': 'md5:edf42b8bd5bc4e5da4db4222c5acb7d6',
237                 'upload_date': '20140122',
238                 'duration': 245.32,
239             },
240             'params': {
241                 # rtmp download
242                 'skip_download': True,
243             },
244             'skip': 'This video is unavailable',
245         },
246         {
247             'url': 'http://www.sat1.de/film/der-ruecktritt/video/im-interview-kai-wiesinger-clip',
248             'info_dict': {
249                 'id': '2906572',
250                 'ext': 'mp4',
251                 'title': 'Im Interview: Kai Wiesinger',
252                 'description': 'md5:e4e5370652ec63b95023e914190b4eb9',
253                 'upload_date': '20140203',
254                 'duration': 522.56,
255             },
256             'params': {
257                 # rtmp download
258                 'skip_download': True,
259             },
260             'skip': 'This video is unavailable',
261         },
262         {
263             'url': 'http://www.kabeleins.de/tv/rosins-restaurants/videos/jagd-auf-fertigkost-im-elsthal-teil-2-ganze-folge',
264             'info_dict': {
265                 'id': '2992323',
266                 'ext': 'mp4',
267                 'title': 'Jagd auf Fertigkost im Elsthal - Teil 2',
268                 'description': 'md5:2669cde3febe9bce13904f701e774eb6',
269                 'upload_date': '20141014',
270                 'duration': 2410.44,
271             },
272             'params': {
273                 # rtmp download
274                 'skip_download': True,
275             },
276             'skip': 'This video is unavailable',
277         },
278         {
279             'url': 'http://www.ran.de/fussball/bundesliga/video/schalke-toennies-moechte-raul-zurueck-ganze-folge',
280             'info_dict': {
281                 'id': '3004256',
282                 'ext': 'mp4',
283                 'title': 'Schalke: Tönnies möchte Raul zurück',
284                 'description': 'md5:4b5b271d9bcde223b54390754c8ece3f',
285                 'upload_date': '20140226',
286                 'duration': 228.96,
287             },
288             'params': {
289                 # rtmp download
290                 'skip_download': True,
291             },
292             'skip': 'This video is unavailable',
293         },
294         {
295             'url': 'http://www.the-voice-of-germany.de/video/31-andreas-kuemmert-rocket-man-clip',
296             'info_dict': {
297                 'id': '2572814',
298                 'ext': 'mp4',
299                 'title': 'Andreas Kümmert: Rocket Man',
300                 'description': 'md5:6ddb02b0781c6adf778afea606652e38',
301                 'upload_date': '20131017',
302                 'duration': 469.88,
303             },
304             'params': {
305                 'skip_download': True,
306             },
307         },
308         {
309             'url': 'http://www.fem.com/wellness/videos/wellness-video-clip-kurztripps-zum-valentinstag.html',
310             'info_dict': {
311                 'id': '2156342',
312                 'ext': 'mp4',
313                 'title': 'Kurztrips zum Valentinstag',
314                 'description': 'Romantischer Kurztrip zum Valentinstag? Nina Heinemann verrät, was sich hier wirklich lohnt.',
315                 'duration': 307.24,
316             },
317             'params': {
318                 'skip_download': True,
319             },
320         },
321         {
322             'url': 'http://www.prosieben.de/tv/joko-gegen-klaas/videos/playlists/episode-8-ganze-folge-playlist',
323             'info_dict': {
324                 'id': '439664',
325                 'title': 'Episode 8 - Ganze Folge - Playlist',
326                 'description': 'md5:63b8963e71f481782aeea877658dec84',
327             },
328             'playlist_count': 2,
329             'skip': 'This video is unavailable',
330         },
331         {
332             'url': 'http://www.7tv.de/circus-halligalli/615-best-of-circus-halligalli-ganze-folge',
333             'info_dict': {
334                 'id': '4187506',
335                 'ext': 'mp4',
336                 'title': 'Best of Circus HalliGalli',
337                 'description': 'md5:8849752efd90b9772c9db6fdf87fb9e9',
338                 'upload_date': '20151229',
339             },
340             'params': {
341                 'skip_download': True,
342             },
343         },
344         {
345             # title in <h2 class="subtitle">
346             'url': 'http://www.prosieben.de/stars/oscar-award/videos/jetzt-erst-enthuellt-das-geheimnis-von-emma-stones-oscar-robe-clip',
347             'info_dict': {
348                 'id': '4895826',
349                 'ext': 'mp4',
350                 'title': 'Jetzt erst enthüllt: Das Geheimnis von Emma Stones Oscar-Robe',
351                 'description': 'md5:e5ace2bc43fadf7b63adc6187e9450b9',
352                 'upload_date': '20170302',
353             },
354             'params': {
355                 'skip_download': True,
356             },
357             'skip': 'geo restricted to Germany',
358         },
359         {
360             # geo restricted to Germany
361             'url': 'http://www.kabeleinsdoku.de/tv/mayday-alarm-im-cockpit/video/102-notlandung-im-hudson-river-ganze-folge',
362             'only_matching': True,
363         },
364         {
365             # geo restricted to Germany
366             'url': 'http://www.sat1gold.de/tv/edel-starck/video/11-staffel-1-episode-1-partner-wider-willen-ganze-folge',
367             'only_matching': True,
368         },
369         {
370             # geo restricted to Germany
371             'url': 'https://www.galileo.tv/video/diese-emojis-werden-oft-missverstanden',
372             'only_matching': True,
373         },
374         {
375             'url': 'http://www.sat1gold.de/tv/edel-starck/playlist/die-gesamte-1-staffel',
376             'only_matching': True,
377         },
378         {
379             'url': 'http://www.advopedia.de/videos/lenssen-klaert-auf/lenssen-klaert-auf-folge-8-staffel-3-feiertage-und-freie-tage',
380             'only_matching': True,
381         },
382     ]
383
384     _TOKEN = 'prosieben'
385     _SALT = '01!8d8F_)r9]4s[qeuXfP%'
386     _CLIENT_NAME = 'kolibri-2.0.19-splec4'
387
388     _ACCESS_ID = 'x_prosiebenmaxx-de'
389     _ENCRYPTION_KEY = 'Eeyeey9oquahthainoofashoyoikosag'
390     _IV = 'Aeluchoc6aevechuipiexeeboowedaok'
391
392     _CLIPID_REGEXES = [
393         r'"clip_id"\s*:\s+"(\d+)"',
394         r'clipid: "(\d+)"',
395         r'clip[iI]d=(\d+)',
396         r'clip[iI][dD]\s*=\s*["\'](\d+)',
397         r"'itemImageUrl'\s*:\s*'/dynamic/thumbnails/full/\d+/(\d+)",
398         r'proMamsId&quot;\s*:\s*&quot;(\d+)',
399         r'proMamsId"\s*:\s*"(\d+)',
400     ]
401     _TITLE_REGEXES = [
402         r'<h2 class="subtitle" itemprop="name">\s*(.+?)</h2>',
403         r'<header class="clearfix">\s*<h3>(.+?)</h3>',
404         r'<!-- start video -->\s*<h1>(.+?)</h1>',
405         r'<h1 class="att-name">\s*(.+?)</h1>',
406         r'<header class="module_header">\s*<h2>([^<]+)</h2>\s*</header>',
407         r'<h2 class="video-title" itemprop="name">\s*(.+?)</h2>',
408         r'<div[^>]+id="veeseoTitle"[^>]*>(.+?)</div>',
409         r'<h2[^>]+class="subtitle"[^>]*>([^<]+)</h2>',
410     ]
411     _DESCRIPTION_REGEXES = [
412         r'<p itemprop="description">\s*(.+?)</p>',
413         r'<div class="videoDecription">\s*<p><strong>Beschreibung</strong>: (.+?)</p>',
414         r'<div class="g-plusone" data-size="medium"></div>\s*</div>\s*</header>\s*(.+?)\s*<footer>',
415         r'<p class="att-description">\s*(.+?)\s*</p>',
416         r'<p class="video-description" itemprop="description">\s*(.+?)</p>',
417         r'<div[^>]+id="veeseoDescription"[^>]*>(.+?)</div>',
418     ]
419     _UPLOAD_DATE_REGEXES = [
420         r'<meta property="og:published_time" content="(.+?)">',
421         r'<span>\s*(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}) \|\s*<span itemprop="duration"',
422         r'<footer>\s*(\d{2}\.\d{2}\.\d{4}) \d{2}:\d{2} Uhr',
423         r'<span style="padding-left: 4px;line-height:20px; color:#404040">(\d{2}\.\d{2}\.\d{4})</span>',
424         r'(\d{2}\.\d{2}\.\d{4}) \| \d{2}:\d{2} Min<br/>',
425     ]
426     _PAGE_TYPE_REGEXES = [
427         r'<meta name="page_type" content="([^"]+)">',
428         r"'itemType'\s*:\s*'([^']*)'",
429     ]
430     _PLAYLIST_ID_REGEXES = [
431         r'content[iI]d=(\d+)',
432         r"'itemId'\s*:\s*'([^']*)'",
433     ]
434     _PLAYLIST_CLIP_REGEXES = [
435         r'(?s)data-qvt=.+?<a href="([^"]+)"',
436     ]
437
438     def _extract_clip(self, url, webpage):
439         clip_id = self._html_search_regex(
440             self._CLIPID_REGEXES, webpage, 'clip id')
441         title = self._html_search_regex(
442             self._TITLE_REGEXES, webpage, 'title',
443             default=None) or self._og_search_title(webpage)
444         info = self._extract_video_info(url, clip_id)
445         description = self._html_search_regex(
446             self._DESCRIPTION_REGEXES, webpage, 'description', default=None)
447         if description is None:
448             description = self._og_search_description(webpage)
449         thumbnail = self._og_search_thumbnail(webpage)
450         upload_date = unified_strdate(self._html_search_regex(
451             self._UPLOAD_DATE_REGEXES, webpage, 'upload date', default=None))
452
453         info.update({
454             'id': clip_id,
455             'title': title,
456             'description': description,
457             'thumbnail': thumbnail,
458             'upload_date': upload_date,
459         })
460         return info
461
462     def _extract_playlist(self, url, webpage):
463         playlist_id = self._html_search_regex(
464             self._PLAYLIST_ID_REGEXES, webpage, 'playlist id')
465         playlist = self._parse_json(
466             self._search_regex(
467                 r'var\s+contentResources\s*=\s*(\[.+?\]);\s*</script',
468                 webpage, 'playlist'),
469             playlist_id)
470         entries = []
471         for item in playlist:
472             clip_id = item.get('id') or item.get('upc')
473             if not clip_id:
474                 continue
475             info = self._extract_video_info(url, clip_id)
476             info.update({
477                 'id': clip_id,
478                 'title': item.get('title') or item.get('teaser', {}).get('headline'),
479                 'description': item.get('teaser', {}).get('description'),
480                 'thumbnail': item.get('poster'),
481                 'duration': float_or_none(item.get('duration')),
482                 'series': item.get('tvShowTitle'),
483                 'uploader': item.get('broadcastPublisher'),
484             })
485             entries.append(info)
486         return self.playlist_result(entries, playlist_id)
487
488     def _real_extract(self, url):
489         video_id = self._match_id(url)
490         webpage = self._download_webpage(url, video_id)
491         page_type = self._search_regex(
492             self._PAGE_TYPE_REGEXES, webpage,
493             'page type', default='clip').lower()
494         if page_type == 'clip':
495             return self._extract_clip(url, webpage)
496         elif page_type == 'playlist':
497             return self._extract_playlist(url, webpage)
498         else:
499             raise ExtractorError(
500                 'Unsupported page type %s' % page_type, expected=True)