]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/svt.py
Add missing python3-setuptools build dependency. closes: #902279.
[youtubedl] / 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>[^/?#&]+)'
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 def adjust_title(info):
183 if info['is_live']:
184 info['title'] = self._live_title(info['title'])
185
186 if data:
187 video_info = try_get(
188 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
189 dict)
190 if video_info:
191 info_dict = self._extract_video(video_info, video_id)
192 info_dict.update({
193 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
194 'thumbnail': thumbnail,
195 })
196 adjust_title(info_dict)
197 return info_dict
198
199 video_id = self._search_regex(
200 r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
201 webpage, 'video id', default=None)
202
203 if video_id:
204 data = self._download_json(
205 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
206 video_id, headers=self.geo_verification_headers())
207 info_dict = self._extract_video(data, video_id)
208 if not info_dict.get('title'):
209 info_dict['title'] = re.sub(
210 r'\s*\|\s*.+?$', '',
211 info_dict.get('episode') or self._og_search_title(webpage))
212 adjust_title(info_dict)
213 return info_dict
214
215
216 class SVTSeriesIE(SVTPlayBaseIE):
217 _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)'
218 _TESTS = [{
219 'url': 'https://www.svtplay.se/rederiet',
220 'info_dict': {
221 'id': 'rederiet',
222 'title': 'Rederiet',
223 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
224 },
225 'playlist_mincount': 318,
226 }, {
227 'url': 'https://www.svtplay.se/rederiet?tab=sasong2',
228 'info_dict': {
229 'id': 'rederiet-sasong2',
230 'title': 'Rederiet - Säsong 2',
231 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
232 },
233 'playlist_count': 12,
234 }]
235
236 @classmethod
237 def suitable(cls, url):
238 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
239
240 def _real_extract(self, url):
241 series_id = self._match_id(url)
242
243 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
244 season_slug = qs.get('tab', [None])[0]
245
246 if season_slug:
247 series_id += '-%s' % season_slug
248
249 webpage = self._download_webpage(
250 url, series_id, 'Downloading series page')
251
252 root = self._parse_json(
253 self._search_regex(
254 self._SVTPLAY_RE, webpage, 'content', group='json'),
255 series_id)
256
257 season_name = None
258
259 entries = []
260 for season in root['relatedVideoContent']['relatedVideosAccordion']:
261 if not isinstance(season, dict):
262 continue
263 if season_slug:
264 if season.get('slug') != season_slug:
265 continue
266 season_name = season.get('name')
267 videos = season.get('videos')
268 if not isinstance(videos, list):
269 continue
270 for video in videos:
271 content_url = video.get('contentUrl')
272 if not content_url or not isinstance(content_url, compat_str):
273 continue
274 entries.append(
275 self.url_result(
276 urljoin(url, content_url),
277 ie=SVTPlayIE.ie_key(),
278 video_title=video.get('title')
279 ))
280
281 metadata = root.get('metaData')
282 if not isinstance(metadata, dict):
283 metadata = {}
284
285 title = metadata.get('title')
286 season_name = season_name or season_slug
287
288 if title and season_name:
289 title = '%s - %s' % (title, season_name)
290 elif season_slug:
291 title = season_slug
292
293 return self.playlist_result(
294 entries, series_id, title, metadata.get('description'))