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