]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/svt.py
[acast] Fix extraction (closes #16118)
[yt-dlp.git] / youtube_dl / 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 (
8 compat_parse_qs,
9 compat_urllib_parse_urlparse,
10 )
11 from ..utils import (
12 determine_ext,
13 dict_get,
14 int_or_none,
15 try_get,
16 urljoin,
17 compat_str,
18 )
19
20
21 class SVTBaseIE(InfoExtractor):
22 _GEO_COUNTRIES = ['SE']
23
24 def _extract_video(self, video_info, video_id):
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_native',
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 if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
49 self.raise_geo_restricted(
50 'This video is only available in Sweden',
51 countries=self._GEO_COUNTRIES)
52 self._sort_formats(formats)
53
54 subtitles = {}
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 if determine_ext(subtitle_url) == 'm3u8':
62 # TODO(yan12125): handle WebVTT in m3u8 manifests
63 continue
64
65 subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
66
67 title = video_info.get('title')
68
69 series = video_info.get('programTitle')
70 season_number = int_or_none(video_info.get('season'))
71 episode = video_info.get('episodeTitle')
72 episode_number = int_or_none(video_info.get('episodeNumber'))
73
74 duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
75 age_limit = None
76 adult = dict_get(
77 video_info, ('inappropriateForChildren', 'blockedForChildren'),
78 skip_false_values=False)
79 if adult is not None:
80 age_limit = 18 if adult else 0
81
82 return {
83 'id': video_id,
84 'title': title,
85 'formats': formats,
86 'subtitles': subtitles,
87 'duration': duration,
88 'age_limit': age_limit,
89 'series': series,
90 'season_number': season_number,
91 'episode': episode,
92 'episode_number': episode_number,
93 }
94
95
96 class 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',
100 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
101 'info_dict': {
102 'id': '2900353',
103 'ext': 'mp4',
104 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
105 'duration': 27,
106 'age_limit': 0,
107 },
108 }
109
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
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')
121
122 info = self._download_json(
123 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
124 article_id)
125
126 info_dict = self._extract_video(info['video'], article_id)
127 info_dict['title'] = info['context']['title']
128 return info_dict
129
130
131 class SVTPlayBaseIE(SVTBaseIE):
132 _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
133
134
135 class SVTPlayIE(SVTPlayBaseIE):
136 IE_DESC = 'SVT Play and Öppet arkiv'
137 _VALID_URL = r'https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp)/(?P<id>[0-9]+)'
138 _TESTS = [{
139 'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
140 'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
141 'info_dict': {
142 'id': '5996901',
143 'ext': 'mp4',
144 'title': 'Flygplan till Haile Selassie',
145 'duration': 3527,
146 'thumbnail': r're:^https?://.*[\.-]jpg$',
147 'age_limit': 0,
148 'subtitles': {
149 'sv': [{
150 'ext': 'wsrt',
151 }]
152 },
153 },
154 }, {
155 # geo restricted to Sweden
156 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
157 'only_matching': True,
158 }, {
159 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
160 'only_matching': True,
161 }]
162
163 def _real_extract(self, url):
164 video_id = self._match_id(url)
165
166 webpage = self._download_webpage(url, video_id)
167
168 data = self._parse_json(
169 self._search_regex(
170 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
171 group='json'),
172 video_id, fatal=False)
173
174 thumbnail = self._og_search_thumbnail(webpage)
175
176 if data:
177 video_info = try_get(
178 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
179 dict)
180 if video_info:
181 info_dict = self._extract_video(video_info, video_id)
182 info_dict.update({
183 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
184 'thumbnail': thumbnail,
185 })
186 return info_dict
187
188 video_id = self._search_regex(
189 r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
190 webpage, 'video id', default=None)
191
192 if video_id:
193 data = self._download_json(
194 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
195 video_id, headers=self.geo_verification_headers())
196 info_dict = self._extract_video(data, video_id)
197 if not info_dict.get('title'):
198 info_dict['title'] = re.sub(
199 r'\s*\|\s*.+?$', '',
200 info_dict.get('episode') or self._og_search_title(webpage))
201 return info_dict
202
203
204 class SVTSeriesIE(SVTPlayBaseIE):
205 _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)'
206 _TESTS = [{
207 'url': 'https://www.svtplay.se/rederiet',
208 'info_dict': {
209 'id': 'rederiet',
210 'title': 'Rederiet',
211 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
212 },
213 'playlist_mincount': 318,
214 }, {
215 'url': 'https://www.svtplay.se/rederiet?tab=sasong2',
216 'info_dict': {
217 'id': 'rederiet-sasong2',
218 'title': 'Rederiet - Säsong 2',
219 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
220 },
221 'playlist_count': 12,
222 }]
223
224 @classmethod
225 def suitable(cls, url):
226 return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
227
228 def _real_extract(self, url):
229 series_id = self._match_id(url)
230
231 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
232 season_slug = qs.get('tab', [None])[0]
233
234 if season_slug:
235 series_id += '-%s' % season_slug
236
237 webpage = self._download_webpage(
238 url, series_id, 'Downloading series page')
239
240 root = self._parse_json(
241 self._search_regex(
242 self._SVTPLAY_RE, webpage, 'content', group='json'),
243 series_id)
244
245 season_name = None
246
247 entries = []
248 for season in root['relatedVideoContent']['relatedVideosAccordion']:
249 if not isinstance(season, dict):
250 continue
251 if season_slug:
252 if season.get('slug') != season_slug:
253 continue
254 season_name = season.get('name')
255 videos = season.get('videos')
256 if not isinstance(videos, list):
257 continue
258 for video in videos:
259 content_url = video.get('contentUrl')
260 if not content_url or not isinstance(content_url, compat_str):
261 continue
262 entries.append(
263 self.url_result(
264 urljoin(url, content_url),
265 ie=SVTPlayIE.ie_key(),
266 video_title=video.get('title')
267 ))
268
269 metadata = root.get('metaData')
270 if not isinstance(metadata, dict):
271 metadata = {}
272
273 title = metadata.get('title')
274 season_name = season_name or season_slug
275
276 if title and season_name:
277 title = '%s - %s' % (title, season_name)
278 elif season_slug:
279 title = season_slug
280
281 return self.playlist_result(
282 entries, series_id, title, metadata.get('description'))