]> jfr.im git - yt-dlp.git/blame - youtube_dlc/extractor/svt.py
Merge branch 'abc' of https://github.com/adrianheine/youtube-dl into adrianheine-abc
[yt-dlp.git] / youtube_dlc / 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,
43e79947 12 str_or_none,
7b393f9c 13 strip_or_none,
23bdae09 14 try_get,
1309b396
PH
15)
16
17
79998cd5 18class SVTBaseIE(InfoExtractor):
4248dad9 19 _GEO_COUNTRIES = ['SE']
6d4c2597 20
23bdae09 21 def _extract_video(self, video_info, video_id):
488ff2dd 22 is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
23 m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
1309b396
PH
24 formats = []
25 for vr in video_info['videoReferences']:
21d21b0c 26 player_type = vr.get('playerType') or vr.get('format')
1309b396 27 vurl = vr['url']
df5ae3eb
S
28 ext = determine_ext(vurl)
29 if ext == 'm3u8':
1309b396
PH
30 formats.extend(self._extract_m3u8_formats(
31 vurl, video_id,
488ff2dd 32 ext='mp4', entry_protocol=m3u8_protocol,
edfd9351 33 m3u8_id=player_type, fatal=False))
df5ae3eb
S
34 elif ext == 'f4m':
35 formats.extend(self._extract_f4m_formats(
36 vurl + '?hdcore=3.3.0', video_id,
edfd9351 37 f4m_id=player_type, fatal=False))
38 elif ext == 'mpd':
39 if player_type == 'dashhbbtv':
40 formats.extend(self._extract_mpd_formats(
41 vurl, video_id, mpd_id=player_type, fatal=False))
1309b396
PH
42 else:
43 formats.append({
edfd9351 44 'format_id': player_type,
1309b396
PH
45 'url': vurl,
46 })
23bdae09 47 if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
04d906ea 48 self.raise_geo_restricted(
4248dad9
S
49 'This video is only available in Sweden',
50 countries=self._GEO_COUNTRIES)
1309b396
PH
51 self._sort_formats(formats)
52
1f16b958 53 subtitles = {}
e4f90ea0 54 subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
594c4d79
S
55 if isinstance(subtitle_references, list):
56 for sr in subtitle_references:
57 subtitle_url = sr.get('url')
e4f90ea0 58 subtitle_lang = sr.get('language', 'sv')
594c4d79 59 if subtitle_url:
e4f90ea0
YCH
60 if determine_ext(subtitle_url) == 'm3u8':
61 # TODO(yan12125): handle WebVTT in m3u8 manifests
62 continue
63
64 subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
1f16b958 65
23bdae09
S
66 title = video_info.get('title')
67
68 series = video_info.get('programTitle')
69 season_number = int_or_none(video_info.get('season'))
70 episode = video_info.get('episodeTitle')
71 episode_number = int_or_none(video_info.get('episodeNumber'))
72
73 duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
74 age_limit = None
75 adult = dict_get(
76 video_info, ('inappropriateForChildren', 'blockedForChildren'),
77 skip_false_values=False)
78 if adult is not None:
79 age_limit = 18 if adult else 0
1309b396
PH
80
81 return {
82 'id': video_id,
23bdae09 83 'title': title,
1309b396 84 'formats': formats,
1f16b958 85 'subtitles': subtitles,
1309b396 86 'duration': duration,
df5ae3eb 87 'age_limit': age_limit,
23bdae09
S
88 'series': series,
89 'season_number': season_number,
90 'episode': episode,
91 'episode_number': episode_number,
488ff2dd 92 'is_live': is_live,
1309b396 93 }
79998cd5
S
94
95
96class SVTIE(SVTBaseIE):
97 _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
98 _TEST = {
99 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
e4f90ea0 100 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
79998cd5
S
101 'info_dict': {
102 'id': '2900353',
e4f90ea0
YCH
103 'ext': 'mp4',
104 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
79998cd5
S
105 'duration': 27,
106 'age_limit': 0,
107 },
108 }
109
bab19a8e
S
110 @staticmethod
111 def _extract_url(webpage):
112 mobj = re.search(
113 r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
114 if mobj:
115 return mobj.group('url')
116
79998cd5
S
117 def _real_extract(self, url):
118 mobj = re.match(self._VALID_URL, url)
119 widget_id = mobj.group('widget_id')
120 article_id = mobj.group('id')
e4f90ea0
YCH
121
122 info = self._download_json(
79998cd5
S
123 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
124 article_id)
125
23bdae09 126 info_dict = self._extract_video(info['video'], article_id)
e4f90ea0
YCH
127 info_dict['title'] = info['context']['title']
128 return info_dict
129
79998cd5 130
1236ac6b
S
131class SVTPlayBaseIE(SVTBaseIE):
132 _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
133
134
135class SVTPlayIE(SVTPlayBaseIE):
79998cd5 136 IE_DESC = 'SVT Play and Öppet arkiv'
7b393f9c
S
137 _VALID_URL = r'''(?x)
138 (?:
139 svt:(?P<svt_id>[^/?#&]+)|
140 https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
141 )
142 '''
23bdae09 143 _TESTS = [{
594c4d79
S
144 'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
145 'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
79998cd5 146 'info_dict': {
594c4d79
S
147 'id': '5996901',
148 'ext': 'mp4',
149 'title': 'Flygplan till Haile Selassie',
150 'duration': 3527,
ec85ded8 151 'thumbnail': r're:^https?://.*[\.-]jpg$',
79998cd5 152 'age_limit': 0,
594c4d79
S
153 'subtitles': {
154 'sv': [{
155 'ext': 'wsrt',
156 }]
157 },
79998cd5 158 },
23bdae09
S
159 }, {
160 # geo restricted to Sweden
161 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
162 'only_matching': True,
3b34ab53
S
163 }, {
164 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
165 'only_matching': True,
488ff2dd 166 }, {
167 'url': 'https://www.svtplay.se/kanaler/svt1',
168 'only_matching': True,
7b393f9c
S
169 }, {
170 'url': 'svt:1376446-003A',
171 'only_matching': True,
172 }, {
173 'url': 'svt:14278044',
174 'only_matching': True,
23bdae09 175 }]
e4f90ea0 176
7b393f9c
S
177 def _adjust_title(self, info):
178 if info['is_live']:
179 info['title'] = self._live_title(info['title'])
180
181 def _extract_by_video_id(self, video_id, webpage=None):
182 data = self._download_json(
e6a25fea 183 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
7b393f9c
S
184 video_id, headers=self.geo_verification_headers())
185 info_dict = self._extract_video(data, video_id)
186 if not info_dict.get('title'):
187 title = dict_get(info_dict, ('episode', 'series'))
188 if not title and webpage:
189 title = re.sub(
190 r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
191 if not title:
192 title = video_id
193 info_dict['title'] = title
194 self._adjust_title(info_dict)
195 return info_dict
196
79998cd5 197 def _real_extract(self, url):
7b393f9c
S
198 mobj = re.match(self._VALID_URL, url)
199 video_id, svt_id = mobj.group('id', 'svt_id')
200
201 if svt_id:
202 return self._extract_by_video_id(svt_id)
e4f90ea0
YCH
203
204 webpage = self._download_webpage(url, video_id)
205
23bdae09
S
206 data = self._parse_json(
207 self._search_regex(
1236ac6b
S
208 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
209 group='json'),
23bdae09 210 video_id, fatal=False)
e4f90ea0
YCH
211
212 thumbnail = self._og_search_thumbnail(webpage)
213
23bdae09
S
214 if data:
215 video_info = try_get(
216 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
217 dict)
218 if video_info:
219 info_dict = self._extract_video(video_info, video_id)
220 info_dict.update({
221 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
222 'thumbnail': thumbnail,
223 })
7b393f9c 224 self._adjust_title(info_dict)
23bdae09
S
225 return info_dict
226
7b393f9c 227 svt_id = self._search_regex(
23bdae09 228 r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
7b393f9c 229 webpage, 'video id')
23bdae09 230
7b393f9c 231 return self._extract_by_video_id(svt_id, webpage)
fd97fa7b
MW
232
233
1236ac6b 234class SVTSeriesIE(SVTPlayBaseIE):
8e4d3f83 235 _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
fd97fa7b
MW
236 _TESTS = [{
237 'url': 'https://www.svtplay.se/rederiet',
238 'info_dict': {
8e4d3f83 239 'id': '14445680',
fd97fa7b 240 'title': 'Rederiet',
8e4d3f83 241 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
fd97fa7b
MW
242 },
243 'playlist_mincount': 318,
df146eb2 244 }, {
8e4d3f83 245 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
df146eb2 246 'info_dict': {
8e4d3f83 247 'id': 'season-2-14445680',
df146eb2 248 'title': 'Rederiet - Säsong 2',
8e4d3f83 249 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
df146eb2 250 },
8e4d3f83 251 'playlist_mincount': 12,
fd97fa7b
MW
252 }]
253
254 @classmethod
255 def suitable(cls, url):
b71bb3ba 256 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
fd97fa7b
MW
257
258 def _real_extract(self, url):
8e4d3f83
RA
259 series_slug, season_id = re.match(self._VALID_URL, url).groups()
260
261 series = self._download_json(
262 'https://api.svt.se/contento/graphql', series_slug,
263 'Downloading series page', query={
264 'query': '''{
265 listablesBySlug(slugs: ["%s"]) {
266 associatedContent(include: [productionPeriod, season]) {
267 items {
268 item {
269 ... on Episode {
270 videoSvtId
271 }
272 }
273 }
274 id
275 name
276 }
277 id
278 longDescription
279 name
280 shortDescription
281 }
282}''' % series_slug,
283 })['data']['listablesBySlug'][0]
df146eb2
S
284
285 season_name = None
fd97fa7b
MW
286
287 entries = []
8e4d3f83 288 for season in series['associatedContent']:
df146eb2
S
289 if not isinstance(season, dict):
290 continue
8e4d3f83
RA
291 if season_id:
292 if season.get('id') != season_id:
df146eb2
S
293 continue
294 season_name = season.get('name')
8e4d3f83
RA
295 items = season.get('items')
296 if not isinstance(items, list):
fd97fa7b 297 continue
8e4d3f83
RA
298 for item in items:
299 video = item.get('item') or {}
300 content_id = video.get('videoSvtId')
301 if not content_id or not isinstance(content_id, compat_str):
fd97fa7b 302 continue
8e4d3f83
RA
303 entries.append(self.url_result(
304 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
b71bb3ba 305
8e4d3f83
RA
306 title = series.get('name')
307 season_name = season_name or season_id
df146eb2
S
308
309 if title and season_name:
310 title = '%s - %s' % (title, season_name)
8e4d3f83
RA
311 elif season_id:
312 title = season_id
df146eb2 313
fd97fa7b 314 return self.playlist_result(
8e4d3f83
RA
315 entries, season_id or series.get('id'), title,
316 dict_get(series, ('longDescription', 'shortDescription')))
7b393f9c
S
317
318
319class SVTPageIE(InfoExtractor):
43e79947 320 _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
7b393f9c 321 _TESTS = [{
43e79947 322 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
7b393f9c 323 'info_dict': {
43e79947
RA
324 'id': '25298267',
325 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
7b393f9c 326 },
43e79947 327 'playlist_count': 4,
7b393f9c 328 }, {
43e79947 329 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
7b393f9c 330 'info_dict': {
43e79947
RA
331 'id': '24243746',
332 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
7b393f9c 333 },
43e79947 334 'playlist_count': 2,
7b393f9c
S
335 }, {
336 # only programTitle
337 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
338 'info_dict': {
43e79947 339 'id': '8439V2K',
7b393f9c
S
340 'ext': 'mp4',
341 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
342 'duration': 27,
343 'age_limit': 0,
344 },
345 }, {
346 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
347 'only_matching': True,
348 }, {
349 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
350 'only_matching': True,
351 }]
352
353 @classmethod
354 def suitable(cls, url):
355 return False if SVTIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
356
357 def _real_extract(self, url):
43e79947 358 path, display_id = re.match(self._VALID_URL, url).groups()
7b393f9c 359
43e79947
RA
360 article = self._download_json(
361 'https://api.svt.se/nss-api/page/' + path, display_id,
362 query={'q': 'articles'})['articles']['content'][0]
7b393f9c 363
43e79947 364 entries = []
7b393f9c 365
43e79947
RA
366 def _process_content(content):
367 if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
368 video_id = compat_str(content['image']['svtId'])
369 entries.append(self.url_result(
370 'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
7b393f9c 371
43e79947
RA
372 for media in article.get('media', []):
373 _process_content(media)
374
375 for obj in article.get('structuredBody', []):
376 _process_content(obj.get('content') or {})
377
378 return self.playlist_result(
379 entries, str_or_none(article.get('id')),
380 strip_or_none(article.get('title')))