Improve geo bypass mechanism
[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 )
13
14
15 class SVTBaseIE(InfoExtractor):
16     _GEO_COUNTRIES = ['SE']
17     def _extract_video(self, video_info, video_id):
18         formats = []
19         for vr in video_info['videoReferences']:
20             player_type = vr.get('playerType') or vr.get('format')
21             vurl = vr['url']
22             ext = determine_ext(vurl)
23             if ext == 'm3u8':
24                 formats.extend(self._extract_m3u8_formats(
25                     vurl, video_id,
26                     ext='mp4', entry_protocol='m3u8_native',
27                     m3u8_id=player_type, fatal=False))
28             elif ext == 'f4m':
29                 formats.extend(self._extract_f4m_formats(
30                     vurl + '?hdcore=3.3.0', video_id,
31                     f4m_id=player_type, fatal=False))
32             elif ext == 'mpd':
33                 if player_type == 'dashhbbtv':
34                     formats.extend(self._extract_mpd_formats(
35                         vurl, video_id, mpd_id=player_type, fatal=False))
36             else:
37                 formats.append({
38                     'format_id': player_type,
39                     'url': vurl,
40                 })
41         if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
42             self.raise_geo_restricted(
43                 'This video is only available in Sweden',
44                 countries=self._GEO_COUNTRIES)
45         self._sort_formats(formats)
46
47         subtitles = {}
48         subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
49         if isinstance(subtitle_references, list):
50             for sr in subtitle_references:
51                 subtitle_url = sr.get('url')
52                 subtitle_lang = sr.get('language', 'sv')
53                 if subtitle_url:
54                     if determine_ext(subtitle_url) == 'm3u8':
55                         # TODO(yan12125): handle WebVTT in m3u8 manifests
56                         continue
57
58                     subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
59
60         title = video_info.get('title')
61
62         series = video_info.get('programTitle')
63         season_number = int_or_none(video_info.get('season'))
64         episode = video_info.get('episodeTitle')
65         episode_number = int_or_none(video_info.get('episodeNumber'))
66
67         duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
68         age_limit = None
69         adult = dict_get(
70             video_info, ('inappropriateForChildren', 'blockedForChildren'),
71             skip_false_values=False)
72         if adult is not None:
73             age_limit = 18 if adult else 0
74
75         return {
76             'id': video_id,
77             'title': title,
78             'formats': formats,
79             'subtitles': subtitles,
80             'duration': duration,
81             'age_limit': age_limit,
82             'series': series,
83             'season_number': season_number,
84             'episode': episode,
85             'episode_number': episode_number,
86         }
87
88
89 class SVTIE(SVTBaseIE):
90     _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
91     _TEST = {
92         'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
93         'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
94         'info_dict': {
95             'id': '2900353',
96             'ext': 'mp4',
97             'title': 'Stjärnorna skojar till det - under SVT-intervjun',
98             'duration': 27,
99             'age_limit': 0,
100         },
101     }
102
103     @staticmethod
104     def _extract_url(webpage):
105         mobj = re.search(
106             r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
107         if mobj:
108             return mobj.group('url')
109
110     def _real_extract(self, url):
111         mobj = re.match(self._VALID_URL, url)
112         widget_id = mobj.group('widget_id')
113         article_id = mobj.group('id')
114
115         info = self._download_json(
116             'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
117             article_id)
118
119         info_dict = self._extract_video(info['video'], article_id)
120         info_dict['title'] = info['context']['title']
121         return info_dict
122
123
124 class SVTPlayIE(SVTBaseIE):
125     IE_DESC = 'SVT Play and Öppet arkiv'
126     _VALID_URL = r'https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp)/(?P<id>[0-9]+)'
127     _TESTS = [{
128         'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
129         'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
130         'info_dict': {
131             'id': '5996901',
132             'ext': 'mp4',
133             'title': 'Flygplan till Haile Selassie',
134             'duration': 3527,
135             'thumbnail': r're:^https?://.*[\.-]jpg$',
136             'age_limit': 0,
137             'subtitles': {
138                 'sv': [{
139                     'ext': 'wsrt',
140                 }]
141             },
142         },
143     }, {
144         # geo restricted to Sweden
145         'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
146         'only_matching': True,
147     }, {
148         'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
149         'only_matching': True,
150     }]
151
152     def _real_extract(self, url):
153         video_id = self._match_id(url)
154
155         webpage = self._download_webpage(url, video_id)
156
157         data = self._parse_json(
158             self._search_regex(
159                 r'root\["__svtplay"\]\s*=\s*([^;]+);',
160                 webpage, 'embedded data', default='{}'),
161             video_id, fatal=False)
162
163         thumbnail = self._og_search_thumbnail(webpage)
164
165         if data:
166             video_info = try_get(
167                 data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
168                 dict)
169             if video_info:
170                 info_dict = self._extract_video(video_info, video_id)
171                 info_dict.update({
172                     'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
173                     'thumbnail': thumbnail,
174                 })
175                 return info_dict
176
177         video_id = self._search_regex(
178             r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
179             webpage, 'video id', default=None)
180
181         if video_id:
182             data = self._download_json(
183                 'http://www.svt.se/videoplayer-api/video/%s' % video_id, video_id)
184             info_dict = self._extract_video(data, video_id)
185             if not info_dict.get('title'):
186                 info_dict['title'] = re.sub(
187                     r'\s*\|\s*.+?$', '',
188                     info_dict.get('episode') or self._og_search_title(webpage))
189             return info_dict