[svtplay:series] Add extractor
[youtube-dl] / 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 ..utils import (
8     determine_ext,
9     dict_get,
10     int_or_none,
11     try_get,
12     urljoin,
13     compat_str,
14 )
15
16
17 class SVTBaseIE(InfoExtractor):
18     _GEO_COUNTRIES = ['SE']
19
20     def _extract_video(self, video_info, video_id):
21         formats = []
22         for vr in video_info['videoReferences']:
23             player_type = vr.get('playerType') or vr.get('format')
24             vurl = vr['url']
25             ext = determine_ext(vurl)
26             if ext == 'm3u8':
27                 formats.extend(self._extract_m3u8_formats(
28                     vurl, video_id,
29                     ext='mp4', entry_protocol='m3u8_native',
30                     m3u8_id=player_type, fatal=False))
31             elif ext == 'f4m':
32                 formats.extend(self._extract_f4m_formats(
33                     vurl + '?hdcore=3.3.0', video_id,
34                     f4m_id=player_type, fatal=False))
35             elif ext == 'mpd':
36                 if player_type == 'dashhbbtv':
37                     formats.extend(self._extract_mpd_formats(
38                         vurl, video_id, mpd_id=player_type, fatal=False))
39             else:
40                 formats.append({
41                     'format_id': player_type,
42                     'url': vurl,
43                 })
44         if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
45             self.raise_geo_restricted(
46                 'This video is only available in Sweden',
47                 countries=self._GEO_COUNTRIES)
48         self._sort_formats(formats)
49
50         subtitles = {}
51         subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
52         if isinstance(subtitle_references, list):
53             for sr in subtitle_references:
54                 subtitle_url = sr.get('url')
55                 subtitle_lang = sr.get('language', 'sv')
56                 if subtitle_url:
57                     if determine_ext(subtitle_url) == 'm3u8':
58                         # TODO(yan12125): handle WebVTT in m3u8 manifests
59                         continue
60
61                     subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
62
63         title = video_info.get('title')
64
65         series = video_info.get('programTitle')
66         season_number = int_or_none(video_info.get('season'))
67         episode = video_info.get('episodeTitle')
68         episode_number = int_or_none(video_info.get('episodeNumber'))
69
70         duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
71         age_limit = None
72         adult = dict_get(
73             video_info, ('inappropriateForChildren', 'blockedForChildren'),
74             skip_false_values=False)
75         if adult is not None:
76             age_limit = 18 if adult else 0
77
78         return {
79             'id': video_id,
80             'title': title,
81             'formats': formats,
82             'subtitles': subtitles,
83             'duration': duration,
84             'age_limit': age_limit,
85             'series': series,
86             'season_number': season_number,
87             'episode': episode,
88             'episode_number': episode_number,
89         }
90
91
92 class SVTIE(SVTBaseIE):
93     _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
94     _TEST = {
95         'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
96         'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
97         'info_dict': {
98             'id': '2900353',
99             'ext': 'mp4',
100             'title': 'Stjärnorna skojar till det - under SVT-intervjun',
101             'duration': 27,
102             'age_limit': 0,
103         },
104     }
105
106     @staticmethod
107     def _extract_url(webpage):
108         mobj = re.search(
109             r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
110         if mobj:
111             return mobj.group('url')
112
113     def _real_extract(self, url):
114         mobj = re.match(self._VALID_URL, url)
115         widget_id = mobj.group('widget_id')
116         article_id = mobj.group('id')
117
118         info = self._download_json(
119             'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
120             article_id)
121
122         info_dict = self._extract_video(info['video'], article_id)
123         info_dict['title'] = info['context']['title']
124         return info_dict
125
126
127 class SVTPlayIE(SVTBaseIE):
128     IE_DESC = 'SVT Play and Öppet arkiv'
129     _VALID_URL = r'https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp)/(?P<id>[0-9]+)'
130     _TESTS = [{
131         'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
132         'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
133         'info_dict': {
134             'id': '5996901',
135             'ext': 'mp4',
136             'title': 'Flygplan till Haile Selassie',
137             'duration': 3527,
138             'thumbnail': r're:^https?://.*[\.-]jpg$',
139             'age_limit': 0,
140             'subtitles': {
141                 'sv': [{
142                     'ext': 'wsrt',
143                 }]
144             },
145         },
146     }, {
147         # geo restricted to Sweden
148         'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
149         'only_matching': True,
150     }, {
151         'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
152         'only_matching': True,
153     }]
154
155     def _real_extract(self, url):
156         video_id = self._match_id(url)
157
158         webpage = self._download_webpage(url, video_id)
159
160         data = self._parse_json(
161             self._search_regex(
162                 r'root\["__svtplay"\]\s*=\s*([^;]+);',
163                 webpage, 'embedded data', default='{}'),
164             video_id, fatal=False)
165
166         thumbnail = self._og_search_thumbnail(webpage)
167
168         if data:
169             video_info = try_get(
170                 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
171                 dict)
172             if video_info:
173                 info_dict = self._extract_video(video_info, video_id)
174                 info_dict.update({
175                     'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
176                     'thumbnail': thumbnail,
177                 })
178                 return info_dict
179
180         video_id = self._search_regex(
181             r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
182             webpage, 'video id', default=None)
183
184         if video_id:
185             data = self._download_json(
186                 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
187                 video_id, headers=self.geo_verification_headers())
188             info_dict = self._extract_video(data, video_id)
189             if not info_dict.get('title'):
190                 info_dict['title'] = re.sub(
191                     r'\s*\|\s*.+?$', '',
192                     info_dict.get('episode') or self._og_search_title(webpage))
193             return info_dict
194
195
196 class SVTPlaylistIE(InfoExtractor):
197     IE_DESC = 'SVT Play serie'
198     _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)'
199     IE_NAME = 'svtplay:serie'
200     _TESTS = [{
201         'url': 'https://www.svtplay.se/rederiet',
202         'info_dict': {
203             'id': 'rederiet',
204             'title': 'Rederiet',
205             'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
206         },
207         'playlist_mincount': 318,
208     }]
209
210     @classmethod
211     def suitable(cls, url):
212         return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTPlaylistIE, cls).suitable(url)
213
214     def _real_extract(self, url):
215         video_id = self._match_id(url)
216
217         page = self._download_webpage(
218             url, video_id,
219             note='Downloading serie page',
220             errnote='unable to fetch serie page')
221
222         root_json = self._search_regex(
223             r'root\[\'__svtplay\'\]\s*=(.+);\n',
224             page, 'root')
225         root = self._parse_json(root_json, video_id)
226
227         metadata = root.get('metaData', {})
228         related_videos_accordion = root['relatedVideoContent']['relatedVideosAccordion']
229
230         entries = []
231         for season in related_videos_accordion:
232             videos = season.get('videos')
233             if not isinstance(videos, list):
234                 continue
235
236             for video in videos:
237                 content_url = video.get('contentUrl')
238                 if not isinstance(content_url, compat_str):
239                     continue
240                 entries.append(
241                     self.url_result(
242                         urljoin(url, content_url),
243                         ie=SVTPlayIE.ie_key(),
244                         video_title=video.get('title')
245                     ))
246
247         return self.playlist_result(
248             entries, video_id, metadata.get('title'), metadata.get('description'))