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