]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/svt.py
[ie/orf:on] Improve extraction (#9677)
[yt-dlp.git] / yt_dlp / extractor / svt.py
CommitLineData
2301b5c1 1import json
df5ae3eb
S
2import re
3
1309b396 4from .common import InfoExtractor
8e4d3f83 5from ..compat import compat_str
1309b396
PH
6from ..utils import (
7 determine_ext,
e4f90ea0 8 dict_get,
23bdae09 9 int_or_none,
2301b5c1 10 traverse_obj,
23bdae09 11 try_get,
2301b5c1 12 unified_timestamp,
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 54
e4f90ea0 55 subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
594c4d79
S
56 if isinstance(subtitle_references, list):
57 for sr in subtitle_references:
58 subtitle_url = sr.get('url')
e4f90ea0 59 subtitle_lang = sr.get('language', 'sv')
594c4d79 60 if subtitle_url:
3f047fc4
F
61 sub = {
62 'url': subtitle_url,
63 }
e4f90ea0 64 if determine_ext(subtitle_url) == 'm3u8':
3f047fc4
F
65 # XXX: no way of testing, is it ever hit?
66 sub['ext'] = 'vtt'
67 subtitles.setdefault(subtitle_lang, []).append(sub)
1f16b958 68
23bdae09
S
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
a0566bbf 76 timestamp = unified_timestamp(rights.get('validFrom'))
23bdae09
S
77 duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
78 age_limit = None
79 adult = dict_get(
80 video_info, ('inappropriateForChildren', 'blockedForChildren'),
81 skip_false_values=False)
82 if adult is not None:
83 age_limit = 18 if adult else 0
1309b396
PH
84
85 return {
86 'id': video_id,
23bdae09 87 'title': title,
1309b396 88 'formats': formats,
1f16b958 89 'subtitles': subtitles,
1309b396 90 'duration': duration,
a0566bbf 91 'timestamp': timestamp,
df5ae3eb 92 'age_limit': age_limit,
23bdae09
S
93 'series': series,
94 'season_number': season_number,
95 'episode': episode,
96 'episode_number': episode_number,
488ff2dd 97 'is_live': is_live,
1309b396 98 }
79998cd5
S
99
100
101class SVTIE(SVTBaseIE):
102 _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
bfd973ec 103 _EMBED_REGEX = [r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % _VALID_URL]
79998cd5
S
104 _TEST = {
105 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
e4f90ea0 106 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
79998cd5
S
107 'info_dict': {
108 'id': '2900353',
e4f90ea0
YCH
109 'ext': 'mp4',
110 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
79998cd5
S
111 'duration': 27,
112 'age_limit': 0,
113 },
114 }
115
116 def _real_extract(self, url):
5ad28e7f 117 mobj = self._match_valid_url(url)
79998cd5
S
118 widget_id = mobj.group('widget_id')
119 article_id = mobj.group('id')
e4f90ea0
YCH
120
121 info = self._download_json(
79998cd5
S
122 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
123 article_id)
124
23bdae09 125 info_dict = self._extract_video(info['video'], article_id)
e4f90ea0
YCH
126 info_dict['title'] = info['context']['title']
127 return info_dict
128
79998cd5 129
1236ac6b
S
130class SVTPlayBaseIE(SVTBaseIE):
131 _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
132
133
134class SVTPlayIE(SVTPlayBaseIE):
79998cd5 135 IE_DESC = 'SVT Play and Öppet arkiv'
7b393f9c
S
136 _VALID_URL = r'''(?x)
137 (?:
a0566bbf 138 (?:
139 svt:|
140 https?://(?:www\.)?svt\.se/barnkanalen/barnplay/[^/]+/
141 )
142 (?P<svt_id>[^/?#&]+)|
7b393f9c 143 https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
41d1cca3 144 (?:.*?(?:modalId|id)=(?P<modal_id>[\da-zA-Z-]+))?
7b393f9c
S
145 )
146 '''
23bdae09 147 _TESTS = [{
421a4595 148 'url': 'https://www.svtplay.se/video/30479064',
a0566bbf 149 'md5': '2382036fd6f8c994856c323fe51c426e',
79998cd5 150 'info_dict': {
421a4595 151 'id': '8zVbDPA',
594c4d79 152 'ext': 'mp4',
421a4595 153 'title': 'Designdrömmar i Stenungsund',
154 'timestamp': 1615770000,
155 'upload_date': '20210315',
156 'duration': 3519,
a0566bbf 157 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
79998cd5 158 'age_limit': 0,
594c4d79
S
159 'subtitles': {
160 'sv': [{
a0566bbf 161 'ext': 'vtt',
594c4d79
S
162 }]
163 },
79998cd5 164 },
a0566bbf 165 'params': {
2301b5c1
MW
166 'skip_download': 'm3u8',
167 },
168 'skip': 'Episode is no longer available',
169 }, {
170 'url': 'https://www.svtplay.se/video/emBxBQj',
171 'md5': '2382036fd6f8c994856c323fe51c426e',
172 'info_dict': {
173 'id': 'eyBd9aj',
174 'ext': 'mp4',
175 'title': '1. Farlig kryssning',
176 'timestamp': 1491019200,
177 'upload_date': '20170401',
178 'duration': 2566,
179 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
180 'age_limit': 0,
181 'episode': '1. Farlig kryssning',
182 'series': 'Rederiet',
183 'subtitles': {
184 'sv': 'count:3'
185 },
186 },
187 'params': {
188 'skip_download': 'm3u8',
189 },
190 }, {
191 'url': 'https://www.svtplay.se/video/jz2rYz7/anders-hansen-moter/james-fallon?info=visa',
192 'info_dict': {
193 'id': 'jvXAGVb',
194 'ext': 'mp4',
195 'title': 'James Fallon',
196 'timestamp': 1673917200,
197 'upload_date': '20230117',
198 'duration': 1081,
199 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
200 'age_limit': 0,
201 'episode': 'James Fallon',
202 'series': 'Anders Hansen möter...',
203 },
204 'params': {
205 'skip_download': 'dash',
a0566bbf 206 },
421a4595 207 }, {
208 'url': 'https://www.svtplay.se/video/30479064/husdrommar/husdrommar-sasong-8-designdrommar-i-stenungsund?modalId=8zVbDPA',
209 'only_matching': True,
41d1cca3 210 }, {
211 'url': 'https://www.svtplay.se/video/30684086/rapport/rapport-24-apr-18-00-7?id=e72gVpa',
212 'only_matching': True,
23bdae09
S
213 }, {
214 # geo restricted to Sweden
215 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
216 'only_matching': True,
3b34ab53
S
217 }, {
218 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
219 'only_matching': True,
488ff2dd 220 }, {
221 'url': 'https://www.svtplay.se/kanaler/svt1',
222 'only_matching': True,
7b393f9c
S
223 }, {
224 'url': 'svt:1376446-003A',
225 'only_matching': True,
226 }, {
227 'url': 'svt:14278044',
228 'only_matching': True,
a0566bbf 229 }, {
230 'url': 'https://www.svt.se/barnkanalen/barnplay/kar/eWv5MLX/',
231 'only_matching': True,
232 }, {
233 'url': 'svt:eWv5MLX',
234 'only_matching': True,
23bdae09 235 }]
e4f90ea0 236
7b393f9c
S
237 def _extract_by_video_id(self, video_id, webpage=None):
238 data = self._download_json(
e6a25fea 239 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
7b393f9c
S
240 video_id, headers=self.geo_verification_headers())
241 info_dict = self._extract_video(data, video_id)
242 if not info_dict.get('title'):
243 title = dict_get(info_dict, ('episode', 'series'))
244 if not title and webpage:
245 title = re.sub(
246 r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
247 if not title:
248 title = video_id
249 info_dict['title'] = title
7b393f9c
S
250 return info_dict
251
79998cd5 252 def _real_extract(self, url):
5ad28e7f 253 mobj = self._match_valid_url(url)
421a4595 254 video_id = mobj.group('id')
255 svt_id = mobj.group('svt_id') or mobj.group('modal_id')
7b393f9c
S
256
257 if svt_id:
258 return self._extract_by_video_id(svt_id)
e4f90ea0
YCH
259
260 webpage = self._download_webpage(url, video_id)
261
23bdae09
S
262 data = self._parse_json(
263 self._search_regex(
1236ac6b
S
264 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
265 group='json'),
23bdae09 266 video_id, fatal=False)
e4f90ea0
YCH
267
268 thumbnail = self._og_search_thumbnail(webpage)
269
23bdae09
S
270 if data:
271 video_info = try_get(
272 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
273 dict)
274 if video_info:
275 info_dict = self._extract_video(video_info, video_id)
276 info_dict.update({
277 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
278 'thumbnail': thumbnail,
279 })
280 return info_dict
281
5ed05f26
S
282 svt_id = try_get(
283 data, lambda x: x['statistics']['dataLake']['content']['id'],
284 compat_str)
285
2301b5c1
MW
286 if not svt_id:
287 nextjs_data = self._search_nextjs_data(webpage, video_id, fatal=False)
288 svt_id = traverse_obj(nextjs_data, (
289 'props', 'urqlState', ..., 'data', {json.loads}, 'detailsPageByPath',
290 'video', 'svtId', {str}), get_all=False)
291
5ed05f26
S
292 if not svt_id:
293 svt_id = self._search_regex(
294 (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
2301b5c1 295 r'<[^>]+\bdata-rt=["\']top-area-play-button["\'][^>]+\bhref=["\'][^"\']*video/[\w-]+/[^"\']*\b(?:modalId|id)=([\w-]+)'),
5ed05f26 296 webpage, 'video id')
23bdae09 297
a0566bbf 298 info_dict = self._extract_by_video_id(svt_id, webpage)
299 info_dict['thumbnail'] = thumbnail
300
301 return info_dict
fd97fa7b
MW
302
303
1236ac6b 304class SVTSeriesIE(SVTPlayBaseIE):
8e4d3f83 305 _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
fd97fa7b
MW
306 _TESTS = [{
307 'url': 'https://www.svtplay.se/rederiet',
308 'info_dict': {
8e4d3f83 309 'id': '14445680',
fd97fa7b 310 'title': 'Rederiet',
8e4d3f83 311 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
fd97fa7b
MW
312 },
313 'playlist_mincount': 318,
df146eb2 314 }, {
8e4d3f83 315 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
df146eb2 316 'info_dict': {
8e4d3f83 317 'id': 'season-2-14445680',
df146eb2 318 'title': 'Rederiet - Säsong 2',
8e4d3f83 319 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
df146eb2 320 },
8e4d3f83 321 'playlist_mincount': 12,
fd97fa7b
MW
322 }]
323
324 @classmethod
325 def suitable(cls, url):
b71bb3ba 326 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
fd97fa7b
MW
327
328 def _real_extract(self, url):
5ad28e7f 329 series_slug, season_id = self._match_valid_url(url).groups()
8e4d3f83
RA
330
331 series = self._download_json(
332 'https://api.svt.se/contento/graphql', series_slug,
333 'Downloading series page', query={
334 'query': '''{
335 listablesBySlug(slugs: ["%s"]) {
336 associatedContent(include: [productionPeriod, season]) {
337 items {
338 item {
339 ... on Episode {
340 videoSvtId
341 }
342 }
343 }
344 id
345 name
346 }
347 id
348 longDescription
349 name
350 shortDescription
351 }
352}''' % series_slug,
353 })['data']['listablesBySlug'][0]
df146eb2
S
354
355 season_name = None
fd97fa7b
MW
356
357 entries = []
8e4d3f83 358 for season in series['associatedContent']:
df146eb2
S
359 if not isinstance(season, dict):
360 continue
8e4d3f83
RA
361 if season_id:
362 if season.get('id') != season_id:
df146eb2
S
363 continue
364 season_name = season.get('name')
8e4d3f83
RA
365 items = season.get('items')
366 if not isinstance(items, list):
fd97fa7b 367 continue
8e4d3f83
RA
368 for item in items:
369 video = item.get('item') or {}
370 content_id = video.get('videoSvtId')
371 if not content_id or not isinstance(content_id, compat_str):
fd97fa7b 372 continue
8e4d3f83
RA
373 entries.append(self.url_result(
374 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
b71bb3ba 375
8e4d3f83
RA
376 title = series.get('name')
377 season_name = season_name or season_id
df146eb2
S
378
379 if title and season_name:
380 title = '%s - %s' % (title, season_name)
8e4d3f83
RA
381 elif season_id:
382 title = season_id
df146eb2 383
fd97fa7b 384 return self.playlist_result(
8e4d3f83
RA
385 entries, season_id or series.get('id'), title,
386 dict_get(series, ('longDescription', 'shortDescription')))
7b393f9c
S
387
388
ddd4b5e1 389class SVTPageIE(SVTBaseIE):
390 _VALID_URL = r'https?://(?:www\.)?svt\.se/(?:[^/?#]+/)*(?P<id>[^/?&#]+)'
7b393f9c 391 _TESTS = [{
ddd4b5e1 392 'url': 'https://www.svt.se/nyheter/lokalt/skane/viktor-18-forlorade-armar-och-ben-i-sepsis-vill-ateruppta-karaten-och-bli-svetsare',
393 'info_dict': {
394 'title': 'Viktor, 18, förlorade armar och ben i sepsis – vill återuppta karaten och bli svetsare',
395 'id': 'viktor-18-forlorade-armar-och-ben-i-sepsis-vill-ateruppta-karaten-och-bli-svetsare',
396 },
397 'playlist_count': 2,
398 }, {
399 'url': 'https://www.svt.se/nyheter/lokalt/skane/forsvarsmakten-om-trafikkaoset-pa-e22-kunde-inte-varit-dar-snabbare',
400 'info_dict': {
401 'id': 'jXvk42E',
402 'title': 'Försvarsmakten om trafikkaoset på E22: Kunde inte varit där snabbare',
403 'ext': 'mp4',
404 "duration": 80,
405 'age_limit': 0,
406 'timestamp': 1704370009,
407 'episode': 'Försvarsmakten om trafikkaoset på E22: Kunde inte varit där snabbare',
408 'series': 'Lokala Nyheter Skåne',
409 'upload_date': '20240104'
410 },
411 'params': {
412 'skip_download': True,
413 }
414 }, {
415 'url': 'https://www.svt.se/nyheter/svtforum/2023-tungt-ar-for-svensk-media',
416 'info_dict': {
417 'title': '2023 tungt år för svensk media',
418 'id': 'ewqAZv4',
419 'ext': 'mp4',
420 "duration": 3074,
421 'age_limit': 0,
422 'series': '',
423 'timestamp': 1702980479,
424 'upload_date': '20231219',
425 'episode': 'Mediestudier'
426 },
427 'params': {
428 'skip_download': True,
429 }
430 }, {
43e79947 431 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
7b393f9c 432 'info_dict': {
43e79947
RA
433 'id': '25298267',
434 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
7b393f9c 435 },
43e79947 436 'playlist_count': 4,
ddd4b5e1 437 'skip': 'Video is gone'
7b393f9c 438 }, {
43e79947 439 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
7b393f9c 440 'info_dict': {
43e79947
RA
441 'id': '24243746',
442 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
7b393f9c 443 },
43e79947 444 'playlist_count': 2,
ddd4b5e1 445 'skip': 'Video is gone'
7b393f9c
S
446 }, {
447 # only programTitle
448 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
449 'info_dict': {
43e79947 450 'id': '8439V2K',
7b393f9c
S
451 'ext': 'mp4',
452 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
453 'duration': 27,
454 'age_limit': 0,
455 },
ddd4b5e1 456 'skip': 'Video is gone'
7b393f9c
S
457 }, {
458 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
459 'only_matching': True,
460 }, {
461 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
462 'only_matching': True,
463 }]
464
465 @classmethod
466 def suitable(cls, url):
a0566bbf 467 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
7b393f9c
S
468
469 def _real_extract(self, url):
ddd4b5e1 470 display_id = self._match_id(url)
7b393f9c 471
ddd4b5e1 472 webpage = self._download_webpage(url, display_id)
473 title = self._og_search_title(webpage)
7b393f9c 474
ddd4b5e1 475 urql_state = self._search_json(
476 r'window\.svt\.nyh\.urqlState\s*=', webpage, 'json data', display_id)
7b393f9c 477
ddd4b5e1 478 data = traverse_obj(urql_state, (..., 'data', {str}, {json.loads}), get_all=False) or {}
7b393f9c 479
ddd4b5e1 480 def entries():
481 for video_id in set(traverse_obj(data, (
482 'page', (('topMedia', 'svtId'), ('body', ..., 'video', 'svtId')), {str}
483 ))):
484 info = self._extract_video(
485 self._download_json(f'https://api.svt.se/video/{video_id}', video_id), video_id)
486 info['title'] = title
487 yield info
43e79947 488
ddd4b5e1 489 return self.playlist_result(entries(), display_id, title)