[go90] detect geo restriction error and pass geo verification headers(closes #16874)
[youtube-dl] / youtube_dl / extractor / go90.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_HTTPError
8 from ..utils import (
9     determine_ext,
10     ExtractorError,
11     int_or_none,
12     parse_age_limit,
13     parse_iso8601,
14 )
15
16
17 class Go90IE(InfoExtractor):
18     _VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a-zA-Z]+)'
19     _TEST = {
20         'url': 'https://www.go90.com/videos/84BUqjLpf9D',
21         'md5': 'efa7670dbbbf21a7b07b360652b24a32',
22         'info_dict': {
23             'id': '84BUqjLpf9D',
24             'ext': 'mp4',
25             'title': 'Daily VICE - Inside The Utah Coalition Against Pornography Convention',
26             'description': 'VICE\'s Karley Sciortino meets with activists who discuss the state\'s strong anti-porn stance. Then, VICE Sports explains NFL contracts.',
27             'timestamp': 1491868800,
28             'upload_date': '20170411',
29             'age_limit': 14,
30         }
31     }
32     _GEO_BYPASS = False
33
34     def _real_extract(self, url):
35         video_id = self._match_id(url)
36
37         try:
38             headers = self.geo_verification_headers()
39             headers.update({
40                 'Content-Type': 'application/json; charset=utf-8',
41             })
42             video_data = self._download_json(
43                 'https://www.go90.com/api/view/items/' + video_id, video_id,
44                 headers=headers, data=b'{"client":"web","device_type":"pc"}')
45         except ExtractorError as e:
46             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
47                 message = self._parse_json(e.cause.read().decode(), None)['error']['message']
48                 if 'region unavailable' in message:
49                     self.raise_geo_restricted(countries=['US'])
50                 raise ExtractorError(message, expected=True)
51             raise
52
53         if video_data.get('requires_drm'):
54             raise ExtractorError('This video is DRM protected.', expected=True)
55         main_video_asset = video_data['main_video_asset']
56
57         episode_number = int_or_none(video_data.get('episode_number'))
58         series = None
59         season = None
60         season_id = None
61         season_number = None
62         for metadata in video_data.get('__children', {}).get('Item', {}).values():
63             if metadata.get('type') == 'show':
64                 series = metadata.get('title')
65             elif metadata.get('type') == 'season':
66                 season = metadata.get('title')
67                 season_id = metadata.get('id')
68                 season_number = int_or_none(metadata.get('season_number'))
69
70         title = episode = video_data.get('title') or series
71         if series and series != title:
72             title = '%s - %s' % (series, title)
73
74         thumbnails = []
75         formats = []
76         subtitles = {}
77         for asset in video_data.get('assets'):
78             if asset.get('id') == main_video_asset:
79                 for source in asset.get('sources', []):
80                     source_location = source.get('location')
81                     if not source_location:
82                         continue
83                     source_type = source.get('type')
84                     if source_type == 'hls':
85                         m3u8_formats = self._extract_m3u8_formats(
86                             source_location, video_id, 'mp4',
87                             'm3u8_native', m3u8_id='hls', fatal=False)
88                         for f in m3u8_formats:
89                             mobj = re.search(r'/hls-(\d+)-(\d+)K', f['url'])
90                             if mobj:
91                                 height, tbr = mobj.groups()
92                                 height = int_or_none(height)
93                                 f.update({
94                                     'height': f.get('height') or height,
95                                     'width': f.get('width') or int_or_none(height / 9.0 * 16.0 if height else None),
96                                     'tbr': f.get('tbr') or int_or_none(tbr),
97                                 })
98                         formats.extend(m3u8_formats)
99                     elif source_type == 'dash':
100                         formats.extend(self._extract_mpd_formats(
101                             source_location, video_id, mpd_id='dash', fatal=False))
102                     else:
103                         formats.append({
104                             'format_id': source.get('name'),
105                             'url': source_location,
106                             'width': int_or_none(source.get('width')),
107                             'height': int_or_none(source.get('height')),
108                             'tbr': int_or_none(source.get('bitrate')),
109                         })
110
111                 for caption in asset.get('caption_metadata', []):
112                     caption_url = caption.get('source_url')
113                     if not caption_url:
114                         continue
115                     subtitles.setdefault(caption.get('language', 'en'), []).append({
116                         'url': caption_url,
117                         'ext': determine_ext(caption_url, 'vtt'),
118                     })
119             elif asset.get('type') == 'image':
120                 asset_location = asset.get('location')
121                 if not asset_location:
122                     continue
123                 thumbnails.append({
124                     'url': asset_location,
125                     'width': int_or_none(asset.get('width')),
126                     'height': int_or_none(asset.get('height')),
127                 })
128         self._sort_formats(formats)
129
130         return {
131             'id': video_id,
132             'title': title,
133             'formats': formats,
134             'thumbnails': thumbnails,
135             'description': video_data.get('short_description'),
136             'like_count': int_or_none(video_data.get('like_count')),
137             'timestamp': parse_iso8601(video_data.get('released_at')),
138             'series': series,
139             'episode': episode,
140             'season': season,
141             'season_id': season_id,
142             'season_number': season_number,
143             'episode_number': episode_number,
144             'subtitles': subtitles,
145             'age_limit': parse_age_limit(video_data.get('rating')),
146         }