[svt] Add support for TV channel live streams (Closes #15279)
[youtube-dl] / youtube_dl / extractor / svt.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_parse_qs,
9     compat_urllib_parse_urlparse,
10 )
11 from ..utils import (
12     determine_ext,
13     dict_get,
14     int_or_none,
15     try_get,
16     urljoin,
17     compat_str,
18 )
19
20
21 class SVTBaseIE(InfoExtractor):
22     _GEO_COUNTRIES = ['SE']
23
24     def _extract_video(self, video_info, video_id):
25         is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
26         m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
27         formats = []
28         for vr in video_info['videoReferences']:
29             player_type = vr.get('playerType') or vr.get('format')
30             vurl = vr['url']
31             ext = determine_ext(vurl)
32             if ext == 'm3u8':
33                 formats.extend(self._extract_m3u8_formats(
34                     vurl, video_id,
35                     ext='mp4', entry_protocol=m3u8_protocol,
36                     m3u8_id=player_type, fatal=False))
37             elif ext == 'f4m':
38                 formats.extend(self._extract_f4m_formats(
39                     vurl + '?hdcore=3.3.0', video_id,
40                     f4m_id=player_type, fatal=False))
41             elif ext == 'mpd':
42                 if player_type == 'dashhbbtv':
43                     formats.extend(self._extract_mpd_formats(
44                         vurl, video_id, mpd_id=player_type, fatal=False))
45             else:
46                 formats.append({
47                     'format_id': player_type,
48                     'url': vurl,
49                 })
50         if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
51             self.raise_geo_restricted(
52                 'This video is only available in Sweden',
53                 countries=self._GEO_COUNTRIES)
54         self._sort_formats(formats)
55
56         subtitles = {}
57         subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
58         if isinstance(subtitle_references, list):
59             for sr in subtitle_references:
60                 subtitle_url = sr.get('url')
61                 subtitle_lang = sr.get('language', 'sv')
62                 if subtitle_url:
63                     if determine_ext(subtitle_url) == 'm3u8':
64                         # TODO(yan12125): handle WebVTT in m3u8 manifests
65                         continue
66
67                     subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
68
69         title = video_info.get('title')
70
71         series = video_info.get('programTitle')
72         season_number = int_or_none(video_info.get('season'))
73         episode = video_info.get('episodeTitle')
74         episode_number = int_or_none(video_info.get('episodeNumber'))
75
76         duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
77         age_limit = None
78         adult = dict_get(
79             video_info, ('inappropriateForChildren', 'blockedForChildren'),
80             skip_false_values=False)
81         if adult is not None:
82             age_limit = 18 if adult else 0
83
84         return {
85             'id': video_id,
86             'title': title,
87             'formats': formats,
88             'subtitles': subtitles,
89             'duration': duration,
90             'age_limit': age_limit,
91             'series': series,
92             'season_number': season_number,
93             'episode': episode,
94             'episode_number': episode_number,
95             'is_live': is_live,
96         }
97
98
99 class SVTIE(SVTBaseIE):
100     _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
101     _TEST = {
102         'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
103         'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
104         'info_dict': {
105             'id': '2900353',
106             'ext': 'mp4',
107             'title': 'Stjärnorna skojar till det - under SVT-intervjun',
108             'duration': 27,
109             'age_limit': 0,
110         },
111     }
112
113     @staticmethod
114     def _extract_url(webpage):
115         mobj = re.search(
116             r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
117         if mobj:
118             return mobj.group('url')
119
120     def _real_extract(self, url):
121         mobj = re.match(self._VALID_URL, url)
122         widget_id = mobj.group('widget_id')
123         article_id = mobj.group('id')
124
125         info = self._download_json(
126             'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
127             article_id)
128
129         info_dict = self._extract_video(info['video'], article_id)
130         info_dict['title'] = info['context']['title']
131         return info_dict
132
133
134 class SVTPlayBaseIE(SVTBaseIE):
135     _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
136
137
138 class SVTPlayIE(SVTPlayBaseIE):
139     IE_DESC = 'SVT Play and Öppet arkiv'
140     _VALID_URL = r'https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>\w+)'
141     _TESTS = [{
142         'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
143         'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
144         'info_dict': {
145             'id': '5996901',
146             'ext': 'mp4',
147             'title': 'Flygplan till Haile Selassie',
148             'duration': 3527,
149             'thumbnail': r're:^https?://.*[\.-]jpg$',
150             'age_limit': 0,
151             'subtitles': {
152                 'sv': [{
153                     'ext': 'wsrt',
154                 }]
155             },
156         },
157     }, {
158         # geo restricted to Sweden
159         'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
160         'only_matching': True,
161     }, {
162         'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
163         'only_matching': True,
164     }, {
165         'url': 'https://www.svtplay.se/kanaler/svt1',
166         'only_matching': True,
167     }]
168
169     def _real_extract(self, url):
170         video_id = self._match_id(url)
171
172         webpage = self._download_webpage(url, video_id)
173
174         data = self._parse_json(
175             self._search_regex(
176                 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
177                 group='json'),
178             video_id, fatal=False)
179
180         thumbnail = self._og_search_thumbnail(webpage)
181
182         if data:
183             video_info = try_get(
184                 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
185                 dict)
186             if video_info:
187                 info_dict = self._extract_video(video_info, video_id)
188                 info_dict.update({
189                     'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
190                     'thumbnail': thumbnail,
191                 })
192                 if info_dict['is_live']:
193                     info_dict['title'] = self._live_title(info_dict['title'])
194                 return info_dict
195
196         video_id = self._search_regex(
197             r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
198             webpage, 'video id', default=None)
199
200         if video_id:
201             data = self._download_json(
202                 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
203                 video_id, headers=self.geo_verification_headers())
204             info_dict = self._extract_video(data, video_id)
205             if not info_dict.get('title'):
206                 info_dict['title'] = re.sub(
207                     r'\s*\|\s*.+?$', '',
208                     info_dict.get('episode') or self._og_search_title(webpage))
209             if info_dict['is_live']:
210                 info_dict['title'] = self._live_title(info_dict['title'])
211             return info_dict
212
213
214 class SVTSeriesIE(SVTPlayBaseIE):
215     _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)'
216     _TESTS = [{
217         'url': 'https://www.svtplay.se/rederiet',
218         'info_dict': {
219             'id': 'rederiet',
220             'title': 'Rederiet',
221             'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
222         },
223         'playlist_mincount': 318,
224     }, {
225         'url': 'https://www.svtplay.se/rederiet?tab=sasong2',
226         'info_dict': {
227             'id': 'rederiet-sasong2',
228             'title': 'Rederiet - Säsong 2',
229             'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
230         },
231         'playlist_count': 12,
232     }]
233
234     @classmethod
235     def suitable(cls, url):
236         return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
237
238     def _real_extract(self, url):
239         series_id = self._match_id(url)
240
241         qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
242         season_slug = qs.get('tab', [None])[0]
243
244         if season_slug:
245             series_id += '-%s' % season_slug
246
247         webpage = self._download_webpage(
248             url, series_id, 'Downloading series page')
249
250         root = self._parse_json(
251             self._search_regex(
252                 self._SVTPLAY_RE, webpage, 'content', group='json'),
253             series_id)
254
255         season_name = None
256
257         entries = []
258         for season in root['relatedVideoContent']['relatedVideosAccordion']:
259             if not isinstance(season, dict):
260                 continue
261             if season_slug:
262                 if season.get('slug') != season_slug:
263                     continue
264                 season_name = season.get('name')
265             videos = season.get('videos')
266             if not isinstance(videos, list):
267                 continue
268             for video in videos:
269                 content_url = video.get('contentUrl')
270                 if not content_url or not isinstance(content_url, compat_str):
271                     continue
272                 entries.append(
273                     self.url_result(
274                         urljoin(url, content_url),
275                         ie=SVTPlayIE.ie_key(),
276                         video_title=video.get('title')
277                     ))
278
279         metadata = root.get('metaData')
280         if not isinstance(metadata, dict):
281             metadata = {}
282
283         title = metadata.get('title')
284         season_name = season_name or season_slug
285
286         if title and season_name:
287             title = '%s - %s' % (title, season_name)
288         elif season_slug:
289             title = season_slug
290
291         return self.playlist_result(
292             entries, series_id, title, metadata.get('description'))