[viewster] Detect video geo restriction
[youtube-dl] / youtube_dl / extractor / viewster.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from .common import InfoExtractor
5 from ..compat import (
6     compat_HTTPError,
7     compat_urllib_request,
8     compat_urllib_parse,
9     compat_urllib_parse_unquote,
10 )
11 from ..utils import (
12     determine_ext,
13     ExtractorError,
14     int_or_none,
15     parse_iso8601,
16     HEADRequest,
17 )
18
19
20 class ViewsterIE(InfoExtractor):
21     _VALID_URL = r'https?://(?:www\.)?viewster\.com/(?:serie|movie)/(?P<id>\d+-\d+-\d+)'
22     _TESTS = [{
23         # movie, Type=Movie
24         'url': 'http://www.viewster.com/movie/1140-11855-000/the-listening-project/',
25         'md5': 'e642d1b27fcf3a4ffa79f194f5adde36',
26         'info_dict': {
27             'id': '1140-11855-000',
28             'ext': 'mp4',
29             'title': 'The listening Project',
30             'description': 'md5:bac720244afd1a8ea279864e67baa071',
31             'timestamp': 1214870400,
32             'upload_date': '20080701',
33             'duration': 4680,
34         },
35     }, {
36         # series episode, Type=Episode
37         'url': 'http://www.viewster.com/serie/1284-19427-001/the-world-and-a-wall/',
38         'md5': '9243079a8531809efe1b089db102c069',
39         'info_dict': {
40             'id': '1284-19427-001',
41             'ext': 'mp4',
42             'title': 'The World and a Wall',
43             'description': 'md5:24814cf74d3453fdf5bfef9716d073e3',
44             'timestamp': 1428192000,
45             'upload_date': '20150405',
46             'duration': 1500,
47         },
48     }, {
49         # serie, Type=Serie
50         'url': 'http://www.viewster.com/serie/1303-19426-000/',
51         'info_dict': {
52             'id': '1303-19426-000',
53             'title': 'Is It Wrong to Try to Pick up Girls in a Dungeon?',
54             'description': 'md5:eeda9bef25b0d524b3a29a97804c2f11',
55         },
56         'playlist_count': 13,
57     }, {
58         # unfinished serie, no Type
59         'url': 'http://www.viewster.com/serie/1284-19427-000/baby-steps-season-2/',
60         'info_dict': {
61             'id': '1284-19427-000',
62             'title': 'Baby Steps—Season 2',
63             'description': 'md5:e7097a8fc97151e25f085c9eb7a1cdb1',
64         },
65         'playlist_mincount': 16,
66     }]
67
68     _ACCEPT_HEADER = 'application/json, text/javascript, */*; q=0.01'
69
70     def _download_json(self, url, video_id, note='Downloading JSON metadata', fatal=True):
71         request = compat_urllib_request.Request(url)
72         request.add_header('Accept', self._ACCEPT_HEADER)
73         request.add_header('Auth-token', self._AUTH_TOKEN)
74         return super(ViewsterIE, self)._download_json(request, video_id, note, fatal=fatal)
75
76     def _real_extract(self, url):
77         video_id = self._match_id(url)
78         # Get 'api_token' cookie
79         self._request_webpage(HEADRequest('http://www.viewster.com/'), video_id)
80         cookies = self._get_cookies('http://www.viewster.com/')
81         self._AUTH_TOKEN = compat_urllib_parse_unquote(cookies['api_token'].value)
82
83         info = self._download_json(
84             'https://public-api.viewster.com/search/%s' % video_id,
85             video_id, 'Downloading entry JSON')
86
87         entry_id = info.get('Id') or info['id']
88
89         # unfinished serie has no Type
90         if info.get('Type') in ['Serie', None]:
91             try:
92                 episodes = self._download_json(
93                     'https://public-api.viewster.com/series/%s/episodes' % entry_id,
94                     video_id, 'Downloading series JSON')
95             except ExtractorError as e:
96                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
97                     self.raise_geo_restricted()
98                 else:
99                     raise
100             entries = [
101                 self.url_result(
102                     'http://www.viewster.com/movie/%s' % episode['OriginId'], 'Viewster')
103                 for episode in episodes]
104             title = (info.get('Title') or info['Synopsis']['Title']).strip()
105             description = info.get('Synopsis', {}).get('Detailed')
106             return self.playlist_result(entries, video_id, title, description)
107
108         formats = []
109         for media_type in ('application/f4m+xml', 'application/x-mpegURL', 'video/mp4'):
110             media = self._download_json(
111                 'https://public-api.viewster.com/movies/%s/video?mediaType=%s'
112                 % (entry_id, compat_urllib_parse.quote(media_type)),
113                 video_id, 'Downloading %s JSON' % media_type, fatal=False)
114             if not media:
115                 continue
116             video_url = media.get('Uri')
117             if not video_url:
118                 continue
119             ext = determine_ext(video_url)
120             if ext == 'f4m':
121                 video_url += '&' if '?' in video_url else '?'
122                 video_url += 'hdcore=3.2.0&plugin=flowplayer-3.2.0.1'
123                 formats.extend(self._extract_f4m_formats(
124                     video_url, video_id, f4m_id='hds'))
125             elif ext == 'm3u8':
126                 formats.extend(self._extract_m3u8_formats(
127                     video_url, video_id, 'mp4', m3u8_id='hls',
128                     fatal=False  # m3u8 sometimes fail
129                 ))
130             else:
131                 format_id = media.get('Bitrate')
132                 f = {
133                     'url': video_url,
134                     'format_id': 'mp4-%s' % format_id,
135                     'height': int_or_none(media.get('Height')),
136                     'width': int_or_none(media.get('Width')),
137                     'preference': 1,
138                 }
139                 if format_id and not f['height']:
140                     f['height'] = int_or_none(self._search_regex(
141                         r'^(\d+)[pP]$', format_id, 'height', default=None))
142                 formats.append(f)
143
144         if not formats and not info.get('LanguageSets') and not info.get('VODSettings'):
145             self.raise_geo_restricted()
146
147         self._sort_formats(formats)
148
149         synopsis = info.get('Synopsis', {})
150         # Prefer title outside synopsis since it's less messy
151         title = (info.get('Title') or synopsis['Title']).strip()
152         description = synopsis.get('Detailed') or info.get('Synopsis', {}).get('Short')
153         duration = int_or_none(info.get('Duration'))
154         timestamp = parse_iso8601(info.get('ReleaseDate'))
155
156         return {
157             'id': video_id,
158             'title': title,
159             'description': description,
160             'timestamp': timestamp,
161             'duration': duration,
162             'formats': formats,
163         }