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