]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/svt.py
[generic] Extract subtitles from video.js (#3156)
[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 subtitles = {}
27 for vr in video_info['videoReferences']:
28 player_type = vr.get('playerType') or vr.get('format')
29 vurl = vr['url']
30 ext = determine_ext(vurl)
31 if ext == 'm3u8':
32 fmts, subs = self._extract_m3u8_formats_and_subtitles(
33 vurl, video_id,
34 ext='mp4', entry_protocol=m3u8_protocol,
35 m3u8_id=player_type, fatal=False)
36 formats.extend(fmts)
37 self._merge_subtitles(subs, target=subtitles)
38 elif ext == 'f4m':
39 formats.extend(self._extract_f4m_formats(
40 vurl + '?hdcore=3.3.0', video_id,
41 f4m_id=player_type, fatal=False))
42 elif ext == 'mpd':
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)
47 else:
48 formats.append({
49 'format_id': player_type,
50 'url': vurl,
51 })
52 rights = try_get(video_info, lambda x: x['rights'], dict) or {}
53 if not formats and rights.get('geoBlockedSweden'):
54 self.raise_geo_restricted(
55 'This video is only available in Sweden',
56 countries=self._GEO_COUNTRIES, metadata_available=True)
57 self._sort_formats(formats)
58
59 subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
60 if isinstance(subtitle_references, list):
61 for sr in subtitle_references:
62 subtitle_url = sr.get('url')
63 subtitle_lang = sr.get('language', 'sv')
64 if subtitle_url:
65 sub = {
66 'url': subtitle_url,
67 }
68 if determine_ext(subtitle_url) == 'm3u8':
69 # XXX: no way of testing, is it ever hit?
70 sub['ext'] = 'vtt'
71 subtitles.setdefault(subtitle_lang, []).append(sub)
72
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
80 timestamp = unified_timestamp(rights.get('validFrom'))
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
88
89 return {
90 'id': video_id,
91 'title': title,
92 'formats': formats,
93 'subtitles': subtitles,
94 'duration': duration,
95 'timestamp': timestamp,
96 'age_limit': age_limit,
97 'series': series,
98 'season_number': season_number,
99 'episode': episode,
100 'episode_number': episode_number,
101 'is_live': is_live,
102 }
103
104
105 class 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',
109 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
110 'info_dict': {
111 'id': '2900353',
112 'ext': 'mp4',
113 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
114 'duration': 27,
115 'age_limit': 0,
116 },
117 }
118
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
126 def _real_extract(self, url):
127 mobj = self._match_valid_url(url)
128 widget_id = mobj.group('widget_id')
129 article_id = mobj.group('id')
130
131 info = self._download_json(
132 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
133 article_id)
134
135 info_dict = self._extract_video(info['video'], article_id)
136 info_dict['title'] = info['context']['title']
137 return info_dict
138
139
140 class SVTPlayBaseIE(SVTBaseIE):
141 _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
142
143
144 class SVTPlayIE(SVTPlayBaseIE):
145 IE_DESC = 'SVT Play and Öppet arkiv'
146 _VALID_URL = r'''(?x)
147 (?:
148 (?:
149 svt:|
150 https?://(?:www\.)?svt\.se/barnkanalen/barnplay/[^/]+/
151 )
152 (?P<svt_id>[^/?#&]+)|
153 https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
154 (?:.*?(?:modalId|id)=(?P<modal_id>[\da-zA-Z-]+))?
155 )
156 '''
157 _TESTS = [{
158 'url': 'https://www.svtplay.se/video/30479064',
159 'md5': '2382036fd6f8c994856c323fe51c426e',
160 'info_dict': {
161 'id': '8zVbDPA',
162 'ext': 'mp4',
163 'title': 'Designdrömmar i Stenungsund',
164 'timestamp': 1615770000,
165 'upload_date': '20210315',
166 'duration': 3519,
167 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
168 'age_limit': 0,
169 'subtitles': {
170 'sv': [{
171 'ext': 'vtt',
172 }]
173 },
174 },
175 'params': {
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 },
181 }, {
182 'url': 'https://www.svtplay.se/video/30479064/husdrommar/husdrommar-sasong-8-designdrommar-i-stenungsund?modalId=8zVbDPA',
183 'only_matching': True,
184 }, {
185 'url': 'https://www.svtplay.se/video/30684086/rapport/rapport-24-apr-18-00-7?id=e72gVpa',
186 'only_matching': True,
187 }, {
188 # geo restricted to Sweden
189 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
190 'only_matching': True,
191 }, {
192 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
193 'only_matching': True,
194 }, {
195 'url': 'https://www.svtplay.se/kanaler/svt1',
196 'only_matching': True,
197 }, {
198 'url': 'svt:1376446-003A',
199 'only_matching': True,
200 }, {
201 'url': 'svt:14278044',
202 'only_matching': True,
203 }, {
204 'url': 'https://www.svt.se/barnkanalen/barnplay/kar/eWv5MLX/',
205 'only_matching': True,
206 }, {
207 'url': 'svt:eWv5MLX',
208 'only_matching': True,
209 }]
210
211 def _extract_by_video_id(self, video_id, webpage=None):
212 data = self._download_json(
213 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
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
224 return info_dict
225
226 def _real_extract(self, url):
227 mobj = self._match_valid_url(url)
228 video_id = mobj.group('id')
229 svt_id = mobj.group('svt_id') or mobj.group('modal_id')
230
231 if svt_id:
232 return self._extract_by_video_id(svt_id)
233
234 webpage = self._download_webpage(url, video_id)
235
236 data = self._parse_json(
237 self._search_regex(
238 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
239 group='json'),
240 video_id, fatal=False)
241
242 thumbnail = self._og_search_thumbnail(webpage)
243
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
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-]+)',
263 r'<[^>]+\bdata-rt=["\']top-area-play-button["\'][^>]+\bhref=["\'][^"\']*video/%s/[^"\']*\b(?:modalId|id)=([\da-zA-Z-]+)' % re.escape(video_id),
264 r'["\']videoSvtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
265 r'["\']videoSvtId\\?["\']\s*:\s*\\?["\']([\da-zA-Z-]+)',
266 r'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"',
267 r'["\']svtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
268 r'["\']svtId\\?["\']\s*:\s*\\?["\']([\da-zA-Z-]+)'),
269 webpage, 'video id')
270
271 info_dict = self._extract_by_video_id(svt_id, webpage)
272 info_dict['thumbnail'] = thumbnail
273
274 return info_dict
275
276
277 class SVTSeriesIE(SVTPlayBaseIE):
278 _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
279 _TESTS = [{
280 'url': 'https://www.svtplay.se/rederiet',
281 'info_dict': {
282 'id': '14445680',
283 'title': 'Rederiet',
284 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
285 },
286 'playlist_mincount': 318,
287 }, {
288 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
289 'info_dict': {
290 'id': 'season-2-14445680',
291 'title': 'Rederiet - Säsong 2',
292 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
293 },
294 'playlist_mincount': 12,
295 }]
296
297 @classmethod
298 def suitable(cls, url):
299 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
300
301 def _real_extract(self, url):
302 series_slug, season_id = self._match_valid_url(url).groups()
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]
327
328 season_name = None
329
330 entries = []
331 for season in series['associatedContent']:
332 if not isinstance(season, dict):
333 continue
334 if season_id:
335 if season.get('id') != season_id:
336 continue
337 season_name = season.get('name')
338 items = season.get('items')
339 if not isinstance(items, list):
340 continue
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):
345 continue
346 entries.append(self.url_result(
347 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
348
349 title = series.get('name')
350 season_name = season_name or season_id
351
352 if title and season_name:
353 title = '%s - %s' % (title, season_name)
354 elif season_id:
355 title = season_id
356
357 return self.playlist_result(
358 entries, season_id or series.get('id'), title,
359 dict_get(series, ('longDescription', 'shortDescription')))
360
361
362 class SVTPageIE(InfoExtractor):
363 _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
364 _TESTS = [{
365 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
366 'info_dict': {
367 'id': '25298267',
368 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
369 },
370 'playlist_count': 4,
371 }, {
372 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
373 'info_dict': {
374 'id': '24243746',
375 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
376 },
377 'playlist_count': 2,
378 }, {
379 # only programTitle
380 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
381 'info_dict': {
382 'id': '8439V2K',
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):
398 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
399
400 def _real_extract(self, url):
401 path, display_id = self._match_valid_url(url).groups()
402
403 article = self._download_json(
404 'https://api.svt.se/nss-api/page/' + path, display_id,
405 query={'q': 'articles'})['articles']['content'][0]
406
407 entries = []
408
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))
414
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')))