]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/svt.py
[ChangeLog] Actualize
[youtube-dl.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 compat_str
8 from ..utils import (
9     determine_ext,
10     dict_get,
11     int_or_none,
12     str_or_none,
13     strip_or_none,
14     try_get,
15 )
16
17
18 class SVTBaseIE(InfoExtractor):
19     _GEO_COUNTRIES = ['SE']
20
21     def _extract_video(self, video_info, video_id):
22         is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
23         m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
24         formats = []
25         for vr in video_info['videoReferences']:
26             player_type = vr.get('playerType') or vr.get('format')
27             vurl = vr['url']
28             ext = determine_ext(vurl)
29             if ext == 'm3u8':
30                 formats.extend(self._extract_m3u8_formats(
31                     vurl, video_id,
32                     ext='mp4', entry_protocol=m3u8_protocol,
33                     m3u8_id=player_type, fatal=False))
34             elif ext == 'f4m':
35                 formats.extend(self._extract_f4m_formats(
36                     vurl + '?hdcore=3.3.0', video_id,
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))
42             else:
43                 formats.append({
44                     'format_id': player_type,
45                     'url': vurl,
46                 })
47         if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
48             self.raise_geo_restricted(
49                 'This video is only available in Sweden',
50                 countries=self._GEO_COUNTRIES)
51         self._sort_formats(formats)
52
53         subtitles = {}
54         subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
55         if isinstance(subtitle_references, list):
56             for sr in subtitle_references:
57                 subtitle_url = sr.get('url')
58                 subtitle_lang = sr.get('language', 'sv')
59                 if subtitle_url:
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})
65
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
80
81         return {
82             'id': video_id,
83             'title': title,
84             'formats': formats,
85             'subtitles': subtitles,
86             'duration': duration,
87             'age_limit': age_limit,
88             'series': series,
89             'season_number': season_number,
90             'episode': episode,
91             'episode_number': episode_number,
92             'is_live': is_live,
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'''(?x)
138                     (?:
139                         svt:(?P<svt_id>[^/?#&]+)|
140                         https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
141                     )
142                     '''
143     _TESTS = [{
144         'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
145         'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
146         'info_dict': {
147             'id': '5996901',
148             'ext': 'mp4',
149             'title': 'Flygplan till Haile Selassie',
150             'duration': 3527,
151             'thumbnail': r're:^https?://.*[\.-]jpg$',
152             'age_limit': 0,
153             'subtitles': {
154                 'sv': [{
155                     'ext': 'wsrt',
156                 }]
157             },
158         },
159     }, {
160         # geo restricted to Sweden
161         'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
162         'only_matching': True,
163     }, {
164         'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
165         'only_matching': True,
166     }, {
167         'url': 'https://www.svtplay.se/kanaler/svt1',
168         'only_matching': True,
169     }, {
170         'url': 'svt:1376446-003A',
171         'only_matching': True,
172     }, {
173         'url': 'svt:14278044',
174         'only_matching': True,
175     }]
176
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(
183             'https://api.svt.se/videoplayer-api/video/%s' % video_id,
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
197     def _real_extract(self, url):
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)
203
204         webpage = self._download_webpage(url, video_id)
205
206         data = self._parse_json(
207             self._search_regex(
208                 self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
209                 group='json'),
210             video_id, fatal=False)
211
212         thumbnail = self._og_search_thumbnail(webpage)
213
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                 })
224                 self._adjust_title(info_dict)
225                 return info_dict
226
227             svt_id = try_get(
228                 data, lambda x: x['statistics']['dataLake']['content']['id'],
229                 compat_str)
230
231         if not svt_id:
232             svt_id = self._search_regex(
233                 (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
234                  r'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"'),
235                 webpage, 'video id')
236
237         return self._extract_by_video_id(svt_id, webpage)
238
239
240 class SVTSeriesIE(SVTPlayBaseIE):
241     _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
242     _TESTS = [{
243         'url': 'https://www.svtplay.se/rederiet',
244         'info_dict': {
245             'id': '14445680',
246             'title': 'Rederiet',
247             'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
248         },
249         'playlist_mincount': 318,
250     }, {
251         'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
252         'info_dict': {
253             'id': 'season-2-14445680',
254             'title': 'Rederiet - Säsong 2',
255             'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
256         },
257         'playlist_mincount': 12,
258     }]
259
260     @classmethod
261     def suitable(cls, url):
262         return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
263
264     def _real_extract(self, url):
265         series_slug, season_id = re.match(self._VALID_URL, url).groups()
266
267         series = self._download_json(
268             'https://api.svt.se/contento/graphql', series_slug,
269             'Downloading series page', query={
270                 'query': '''{
271   listablesBySlug(slugs: ["%s"]) {
272     associatedContent(include: [productionPeriod, season]) {
273       items {
274         item {
275           ... on Episode {
276             videoSvtId
277           }
278         }
279       }
280       id
281       name
282     }
283     id
284     longDescription
285     name
286     shortDescription
287   }
288 }''' % series_slug,
289             })['data']['listablesBySlug'][0]
290
291         season_name = None
292
293         entries = []
294         for season in series['associatedContent']:
295             if not isinstance(season, dict):
296                 continue
297             if season_id:
298                 if season.get('id') != season_id:
299                     continue
300                 season_name = season.get('name')
301             items = season.get('items')
302             if not isinstance(items, list):
303                 continue
304             for item in items:
305                 video = item.get('item') or {}
306                 content_id = video.get('videoSvtId')
307                 if not content_id or not isinstance(content_id, compat_str):
308                     continue
309                 entries.append(self.url_result(
310                     'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
311
312         title = series.get('name')
313         season_name = season_name or season_id
314
315         if title and season_name:
316             title = '%s - %s' % (title, season_name)
317         elif season_id:
318             title = season_id
319
320         return self.playlist_result(
321             entries, season_id or series.get('id'), title,
322             dict_get(series, ('longDescription', 'shortDescription')))
323
324
325 class SVTPageIE(InfoExtractor):
326     _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
327     _TESTS = [{
328         'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
329         'info_dict': {
330             'id': '25298267',
331             'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
332         },
333         'playlist_count': 4,
334     }, {
335         'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
336         'info_dict': {
337             'id': '24243746',
338             'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
339         },
340         'playlist_count': 2,
341     }, {
342         # only programTitle
343         'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
344         'info_dict': {
345             'id': '8439V2K',
346             'ext': 'mp4',
347             'title': 'Stjärnorna skojar till det - under SVT-intervjun',
348             'duration': 27,
349             'age_limit': 0,
350         },
351     }, {
352         'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
353         'only_matching': True,
354     }, {
355         'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
356         'only_matching': True,
357     }]
358
359     @classmethod
360     def suitable(cls, url):
361         return False if SVTIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
362
363     def _real_extract(self, url):
364         path, display_id = re.match(self._VALID_URL, url).groups()
365
366         article = self._download_json(
367             'https://api.svt.se/nss-api/page/' + path, display_id,
368             query={'q': 'articles'})['articles']['content'][0]
369
370         entries = []
371
372         def _process_content(content):
373             if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
374                 video_id = compat_str(content['image']['svtId'])
375                 entries.append(self.url_result(
376                     'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
377
378         for media in article.get('media', []):
379             _process_content(media)
380
381         for obj in article.get('structuredBody', []):
382             _process_content(obj.get('content') or {})
383
384         return self.playlist_result(
385             entries, str_or_none(article.get('id')),
386             strip_or_none(article.get('title')))