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