]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/svt.py
[extractor/generic] Don't report redirect to https
[yt-dlp.git] / yt_dlp / extractor / svt.py
CommitLineData
df5ae3eb
S
1import re
2
1309b396 3from .common import InfoExtractor
8e4d3f83 4from ..compat import compat_str
1309b396
PH
5from ..utils import (
6 determine_ext,
e4f90ea0 7 dict_get,
23bdae09 8 int_or_none,
a0566bbf 9 unified_timestamp,
43e79947 10 str_or_none,
7b393f9c 11 strip_or_none,
23bdae09 12 try_get,
1309b396
PH
13)
14
15
79998cd5 16class SVTBaseIE(InfoExtractor):
4248dad9 17 _GEO_COUNTRIES = ['SE']
6d4c2597 18
23bdae09 19 def _extract_video(self, video_info, video_id):
488ff2dd 20 is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
21 m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
1309b396 22 formats = []
3f047fc4 23 subtitles = {}
1309b396 24 for vr in video_info['videoReferences']:
21d21b0c 25 player_type = vr.get('playerType') or vr.get('format')
1309b396 26 vurl = vr['url']
df5ae3eb
S
27 ext = determine_ext(vurl)
28 if ext == 'm3u8':
3f047fc4 29 fmts, subs = self._extract_m3u8_formats_and_subtitles(
1309b396 30 vurl, video_id,
488ff2dd 31 ext='mp4', entry_protocol=m3u8_protocol,
3f047fc4
F
32 m3u8_id=player_type, fatal=False)
33 formats.extend(fmts)
34 self._merge_subtitles(subs, target=subtitles)
df5ae3eb
S
35 elif ext == 'f4m':
36 formats.extend(self._extract_f4m_formats(
37 vurl + '?hdcore=3.3.0', video_id,
edfd9351 38 f4m_id=player_type, fatal=False))
39 elif ext == 'mpd':
3f047fc4
F
40 fmts, subs = self._extract_mpd_formats_and_subtitles(
41 vurl, video_id, mpd_id=player_type, fatal=False)
42 formats.extend(fmts)
43 self._merge_subtitles(subs, target=subtitles)
1309b396
PH
44 else:
45 formats.append({
edfd9351 46 'format_id': player_type,
1309b396
PH
47 'url': vurl,
48 })
a0566bbf 49 rights = try_get(video_info, lambda x: x['rights'], dict) or {}
50 if not formats and rights.get('geoBlockedSweden'):
04d906ea 51 self.raise_geo_restricted(
4248dad9 52 'This video is only available in Sweden',
b7da73eb 53 countries=self._GEO_COUNTRIES, metadata_available=True)
1309b396
PH
54 self._sort_formats(formats)
55
e4f90ea0 56 subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
594c4d79
S
57 if isinstance(subtitle_references, list):
58 for sr in subtitle_references:
59 subtitle_url = sr.get('url')
e4f90ea0 60 subtitle_lang = sr.get('language', 'sv')
594c4d79 61 if subtitle_url:
3f047fc4
F
62 sub = {
63 'url': subtitle_url,
64 }
e4f90ea0 65 if determine_ext(subtitle_url) == 'm3u8':
3f047fc4
F
66 # XXX: no way of testing, is it ever hit?
67 sub['ext'] = 'vtt'
68 subtitles.setdefault(subtitle_lang, []).append(sub)
1f16b958 69
23bdae09
S
70 title = video_info.get('title')
71
72 series = video_info.get('programTitle')
73 season_number = int_or_none(video_info.get('season'))
74 episode = video_info.get('episodeTitle')
75 episode_number = int_or_none(video_info.get('episodeNumber'))
76
a0566bbf 77 timestamp = unified_timestamp(rights.get('validFrom'))
23bdae09
S
78 duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
79 age_limit = None
80 adult = dict_get(
81 video_info, ('inappropriateForChildren', 'blockedForChildren'),
82 skip_false_values=False)
83 if adult is not None:
84 age_limit = 18 if adult else 0
1309b396
PH
85
86 return {
87 'id': video_id,
23bdae09 88 'title': title,
1309b396 89 'formats': formats,
1f16b958 90 'subtitles': subtitles,
1309b396 91 'duration': duration,
a0566bbf 92 'timestamp': timestamp,
df5ae3eb 93 'age_limit': age_limit,
23bdae09
S
94 'series': series,
95 'season_number': season_number,
96 'episode': episode,
97 'episode_number': episode_number,
488ff2dd 98 'is_live': is_live,
1309b396 99 }
79998cd5
S
100
101
102class SVTIE(SVTBaseIE):
103 _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
bfd973ec 104 _EMBED_REGEX = [r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % _VALID_URL]
79998cd5
S
105 _TEST = {
106 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
e4f90ea0 107 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
79998cd5
S
108 'info_dict': {
109 'id': '2900353',
e4f90ea0
YCH
110 'ext': 'mp4',
111 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
79998cd5
S
112 'duration': 27,
113 'age_limit': 0,
114 },
115 }
116
117 def _real_extract(self, url):
5ad28e7f 118 mobj = self._match_valid_url(url)
79998cd5
S
119 widget_id = mobj.group('widget_id')
120 article_id = mobj.group('id')
e4f90ea0
YCH
121
122 info = self._download_json(
79998cd5
S
123 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
124 article_id)
125
23bdae09 126 info_dict = self._extract_video(info['video'], article_id)
e4f90ea0
YCH
127 info_dict['title'] = info['context']['title']
128 return info_dict
129
79998cd5 130
1236ac6b
S
131class SVTPlayBaseIE(SVTBaseIE):
132 _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
133
134
135class SVTPlayIE(SVTPlayBaseIE):
79998cd5 136 IE_DESC = 'SVT Play and Öppet arkiv'
7b393f9c
S
137 _VALID_URL = r'''(?x)
138 (?:
a0566bbf 139 (?:
140 svt:|
141 https?://(?:www\.)?svt\.se/barnkanalen/barnplay/[^/]+/
142 )
143 (?P<svt_id>[^/?#&]+)|
7b393f9c 144 https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
41d1cca3 145 (?:.*?(?:modalId|id)=(?P<modal_id>[\da-zA-Z-]+))?
7b393f9c
S
146 )
147 '''
23bdae09 148 _TESTS = [{
421a4595 149 'url': 'https://www.svtplay.se/video/30479064',
a0566bbf 150 'md5': '2382036fd6f8c994856c323fe51c426e',
79998cd5 151 'info_dict': {
421a4595 152 'id': '8zVbDPA',
594c4d79 153 'ext': 'mp4',
421a4595 154 'title': 'Designdrömmar i Stenungsund',
155 'timestamp': 1615770000,
156 'upload_date': '20210315',
157 'duration': 3519,
a0566bbf 158 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
79998cd5 159 'age_limit': 0,
594c4d79
S
160 'subtitles': {
161 'sv': [{
a0566bbf 162 'ext': 'vtt',
594c4d79
S
163 }]
164 },
79998cd5 165 },
a0566bbf 166 'params': {
a0566bbf 167 # skip for now due to download test asserts that segment is > 10000 bytes and svt uses
168 # init segments that are smaller
169 # AssertionError: Expected test_SVTPlay_jNwpV9P.mp4 to be at least 9.77KiB, but it's only 864.00B
170 'skip_download': True,
171 },
421a4595 172 }, {
173 'url': 'https://www.svtplay.se/video/30479064/husdrommar/husdrommar-sasong-8-designdrommar-i-stenungsund?modalId=8zVbDPA',
174 'only_matching': True,
41d1cca3 175 }, {
176 'url': 'https://www.svtplay.se/video/30684086/rapport/rapport-24-apr-18-00-7?id=e72gVpa',
177 'only_matching': True,
23bdae09
S
178 }, {
179 # geo restricted to Sweden
180 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
181 'only_matching': True,
3b34ab53
S
182 }, {
183 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
184 'only_matching': True,
488ff2dd 185 }, {
186 'url': 'https://www.svtplay.se/kanaler/svt1',
187 'only_matching': True,
7b393f9c
S
188 }, {
189 'url': 'svt:1376446-003A',
190 'only_matching': True,
191 }, {
192 'url': 'svt:14278044',
193 'only_matching': True,
a0566bbf 194 }, {
195 'url': 'https://www.svt.se/barnkanalen/barnplay/kar/eWv5MLX/',
196 'only_matching': True,
197 }, {
198 'url': 'svt:eWv5MLX',
199 'only_matching': True,
23bdae09 200 }]
e4f90ea0 201
7b393f9c
S
202 def _extract_by_video_id(self, video_id, webpage=None):
203 data = self._download_json(
e6a25fea 204 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
7b393f9c
S
205 video_id, headers=self.geo_verification_headers())
206 info_dict = self._extract_video(data, video_id)
207 if not info_dict.get('title'):
208 title = dict_get(info_dict, ('episode', 'series'))
209 if not title and webpage:
210 title = re.sub(
211 r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
212 if not title:
213 title = video_id
214 info_dict['title'] = title
7b393f9c
S
215 return info_dict
216
79998cd5 217 def _real_extract(self, url):
5ad28e7f 218 mobj = self._match_valid_url(url)
421a4595 219 video_id = mobj.group('id')
220 svt_id = mobj.group('svt_id') or mobj.group('modal_id')
7b393f9c
S
221
222 if svt_id:
223 return self._extract_by_video_id(svt_id)
e4f90ea0
YCH
224
225 webpage = self._download_webpage(url, video_id)
226
23bdae09
S
227 data = self._parse_json(
228 self._search_regex(
1236ac6b
S
229 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
230 group='json'),
23bdae09 231 video_id, fatal=False)
e4f90ea0
YCH
232
233 thumbnail = self._og_search_thumbnail(webpage)
234
23bdae09
S
235 if data:
236 video_info = try_get(
237 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
238 dict)
239 if video_info:
240 info_dict = self._extract_video(video_info, video_id)
241 info_dict.update({
242 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
243 'thumbnail': thumbnail,
244 })
245 return info_dict
246
5ed05f26
S
247 svt_id = try_get(
248 data, lambda x: x['statistics']['dataLake']['content']['id'],
249 compat_str)
250
251 if not svt_id:
252 svt_id = self._search_regex(
253 (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
41d1cca3 254 r'<[^>]+\bdata-rt=["\']top-area-play-button["\'][^>]+\bhref=["\'][^"\']*video/%s/[^"\']*\b(?:modalId|id)=([\da-zA-Z-]+)' % re.escape(video_id),
95c98100 255 r'["\']videoSvtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
2181983a 256 r'["\']videoSvtId\\?["\']\s*:\s*\\?["\']([\da-zA-Z-]+)',
95c98100 257 r'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"',
2181983a 258 r'["\']svtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
259 r'["\']svtId\\?["\']\s*:\s*\\?["\']([\da-zA-Z-]+)'),
5ed05f26 260 webpage, 'video id')
23bdae09 261
a0566bbf 262 info_dict = self._extract_by_video_id(svt_id, webpage)
263 info_dict['thumbnail'] = thumbnail
264
265 return info_dict
fd97fa7b
MW
266
267
1236ac6b 268class SVTSeriesIE(SVTPlayBaseIE):
8e4d3f83 269 _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
fd97fa7b
MW
270 _TESTS = [{
271 'url': 'https://www.svtplay.se/rederiet',
272 'info_dict': {
8e4d3f83 273 'id': '14445680',
fd97fa7b 274 'title': 'Rederiet',
8e4d3f83 275 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
fd97fa7b
MW
276 },
277 'playlist_mincount': 318,
df146eb2 278 }, {
8e4d3f83 279 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
df146eb2 280 'info_dict': {
8e4d3f83 281 'id': 'season-2-14445680',
df146eb2 282 'title': 'Rederiet - Säsong 2',
8e4d3f83 283 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
df146eb2 284 },
8e4d3f83 285 'playlist_mincount': 12,
fd97fa7b
MW
286 }]
287
288 @classmethod
289 def suitable(cls, url):
b71bb3ba 290 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
fd97fa7b
MW
291
292 def _real_extract(self, url):
5ad28e7f 293 series_slug, season_id = self._match_valid_url(url).groups()
8e4d3f83
RA
294
295 series = self._download_json(
296 'https://api.svt.se/contento/graphql', series_slug,
297 'Downloading series page', query={
298 'query': '''{
299 listablesBySlug(slugs: ["%s"]) {
300 associatedContent(include: [productionPeriod, season]) {
301 items {
302 item {
303 ... on Episode {
304 videoSvtId
305 }
306 }
307 }
308 id
309 name
310 }
311 id
312 longDescription
313 name
314 shortDescription
315 }
316}''' % series_slug,
317 })['data']['listablesBySlug'][0]
df146eb2
S
318
319 season_name = None
fd97fa7b
MW
320
321 entries = []
8e4d3f83 322 for season in series['associatedContent']:
df146eb2
S
323 if not isinstance(season, dict):
324 continue
8e4d3f83
RA
325 if season_id:
326 if season.get('id') != season_id:
df146eb2
S
327 continue
328 season_name = season.get('name')
8e4d3f83
RA
329 items = season.get('items')
330 if not isinstance(items, list):
fd97fa7b 331 continue
8e4d3f83
RA
332 for item in items:
333 video = item.get('item') or {}
334 content_id = video.get('videoSvtId')
335 if not content_id or not isinstance(content_id, compat_str):
fd97fa7b 336 continue
8e4d3f83
RA
337 entries.append(self.url_result(
338 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
b71bb3ba 339
8e4d3f83
RA
340 title = series.get('name')
341 season_name = season_name or season_id
df146eb2
S
342
343 if title and season_name:
344 title = '%s - %s' % (title, season_name)
8e4d3f83
RA
345 elif season_id:
346 title = season_id
df146eb2 347
fd97fa7b 348 return self.playlist_result(
8e4d3f83
RA
349 entries, season_id or series.get('id'), title,
350 dict_get(series, ('longDescription', 'shortDescription')))
7b393f9c
S
351
352
353class SVTPageIE(InfoExtractor):
43e79947 354 _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
7b393f9c 355 _TESTS = [{
43e79947 356 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
7b393f9c 357 'info_dict': {
43e79947
RA
358 'id': '25298267',
359 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
7b393f9c 360 },
43e79947 361 'playlist_count': 4,
7b393f9c 362 }, {
43e79947 363 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
7b393f9c 364 'info_dict': {
43e79947
RA
365 'id': '24243746',
366 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
7b393f9c 367 },
43e79947 368 'playlist_count': 2,
7b393f9c
S
369 }, {
370 # only programTitle
371 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
372 'info_dict': {
43e79947 373 'id': '8439V2K',
7b393f9c
S
374 'ext': 'mp4',
375 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
376 'duration': 27,
377 'age_limit': 0,
378 },
379 }, {
380 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
381 'only_matching': True,
382 }, {
383 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
384 'only_matching': True,
385 }]
386
387 @classmethod
388 def suitable(cls, url):
a0566bbf 389 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
7b393f9c
S
390
391 def _real_extract(self, url):
5ad28e7f 392 path, display_id = self._match_valid_url(url).groups()
7b393f9c 393
43e79947
RA
394 article = self._download_json(
395 'https://api.svt.se/nss-api/page/' + path, display_id,
396 query={'q': 'articles'})['articles']['content'][0]
7b393f9c 397
43e79947 398 entries = []
7b393f9c 399
43e79947
RA
400 def _process_content(content):
401 if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
402 video_id = compat_str(content['image']['svtId'])
403 entries.append(self.url_result(
404 'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
7b393f9c 405
43e79947
RA
406 for media in article.get('media', []):
407 _process_content(media)
408
409 for obj in article.get('structuredBody', []):
410 _process_content(obj.get('content') or {})
411
412 return self.playlist_result(
413 entries, str_or_none(article.get('id')),
414 strip_or_none(article.get('title')))