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