Improve geo bypass mechanism
[youtube-dl] / youtube_dl / extractor / go.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .adobepass import AdobePassIE
7 from ..utils import (
8     int_or_none,
9     determine_ext,
10     parse_age_limit,
11     urlencode_postdata,
12     ExtractorError,
13 )
14
15
16 class GoIE(AdobePassIE):
17     _SITE_INFO = {
18         'abc': {
19             'brand': '001',
20             'requestor_id': 'ABC',
21         },
22         'freeform': {
23             'brand': '002',
24             'requestor_id': 'ABCFamily',
25         },
26         'watchdisneychannel': {
27             'brand': '004',
28             'requestor_id': 'Disney',
29         },
30         'watchdisneyjunior': {
31             'brand': '008',
32             'requestor_id': 'DisneyJunior',
33         },
34         'watchdisneyxd': {
35             'brand': '009',
36             'requestor_id': 'DisneyXD',
37         }
38     }
39     _VALID_URL = r'https?://(?:(?P<sub_domain>%s)\.)?go\.com/(?:[^/]+/)*(?:vdka(?P<id>\w+)|season-\d+/\d+-(?P<display_id>[^/?#]+))' % '|'.join(_SITE_INFO.keys())
40     _GEO_COUNTRIES = ['US']
41     _TESTS = [{
42         'url': 'http://abc.go.com/shows/castle/video/most-recent/vdka0_g86w5onx',
43         'info_dict': {
44             'id': '0_g86w5onx',
45             'ext': 'mp4',
46             'title': 'Sneak Peek: Language Arts',
47             'description': 'md5:7dcdab3b2d17e5217c953256af964e9c',
48         },
49         'params': {
50             # m3u8 download
51             'skip_download': True,
52         },
53     }, {
54         'url': 'http://abc.go.com/shows/after-paradise/video/most-recent/vdka3335601',
55         'only_matching': True,
56     }]
57
58     def _real_extract(self, url):
59         sub_domain, video_id, display_id = re.match(self._VALID_URL, url).groups()
60         if not video_id:
61             webpage = self._download_webpage(url, display_id)
62             video_id = self._search_regex(
63                 # There may be inner quotes, e.g. data-video-id="'VDKA3609139'"
64                 # from http://freeform.go.com/shows/shadowhunters/episodes/season-2/1-this-guilty-blood
65                 r'data-video-id=["\']*VDKA(\w+)', webpage, 'video id')
66         site_info = self._SITE_INFO[sub_domain]
67         brand = site_info['brand']
68         video_data = self._download_json(
69             'http://api.contents.watchabc.go.com/vp2/ws/contents/3000/videos/%s/001/-1/-1/-1/%s/-1/-1.json' % (brand, video_id),
70             video_id)['video'][0]
71         title = video_data['title']
72
73         formats = []
74         for asset in video_data.get('assets', {}).get('asset', []):
75             asset_url = asset.get('value')
76             if not asset_url:
77                 continue
78             format_id = asset.get('format')
79             ext = determine_ext(asset_url)
80             if ext == 'm3u8':
81                 video_type = video_data.get('type')
82                 if video_type == 'lf':
83                     data = {
84                         'video_id': video_data['id'],
85                         'video_type': video_type,
86                         'brand': brand,
87                         'device': '001',
88                     }
89                     if video_data.get('accesslevel') == '1':
90                         requestor_id = site_info['requestor_id']
91                         resource = self._get_mvpd_resource(
92                             requestor_id, title, video_id, None)
93                         auth = self._extract_mvpd_auth(
94                             url, video_id, requestor_id, resource)
95                         data.update({
96                             'token': auth,
97                             'token_type': 'ap',
98                             'adobe_requestor_id': requestor_id,
99                         })
100                     entitlement = self._download_json(
101                         'https://api.entitlement.watchabc.go.com/vp2/ws-secure/entitlement/2020/authorize.json',
102                         video_id, data=urlencode_postdata(data), headers=self.geo_verification_headers())
103                     errors = entitlement.get('errors', {}).get('errors', [])
104                     if errors:
105                         for error in errors:
106                             if error.get('code') == 1002:
107                                 self.raise_geo_restricted(
108                                     error['message'], countries=self._GEO_COUNTRIES)
109                         error_message = ', '.join([error['message'] for error in errors])
110                         raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
111                     asset_url += '?' + entitlement['uplynkData']['sessionKey']
112                 formats.extend(self._extract_m3u8_formats(
113                     asset_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False))
114             else:
115                 formats.append({
116                     'format_id': format_id,
117                     'url': asset_url,
118                     'ext': ext,
119                 })
120         self._sort_formats(formats)
121
122         subtitles = {}
123         for cc in video_data.get('closedcaption', {}).get('src', []):
124             cc_url = cc.get('value')
125             if not cc_url:
126                 continue
127             ext = determine_ext(cc_url)
128             if ext == 'xml':
129                 ext = 'ttml'
130             subtitles.setdefault(cc.get('lang'), []).append({
131                 'url': cc_url,
132                 'ext': ext,
133             })
134
135         thumbnails = []
136         for thumbnail in video_data.get('thumbnails', {}).get('thumbnail', []):
137             thumbnail_url = thumbnail.get('value')
138             if not thumbnail_url:
139                 continue
140             thumbnails.append({
141                 'url': thumbnail_url,
142                 'width': int_or_none(thumbnail.get('width')),
143                 'height': int_or_none(thumbnail.get('height')),
144             })
145
146         return {
147             'id': video_id,
148             'title': title,
149             'description': video_data.get('longdescription') or video_data.get('description'),
150             'duration': int_or_none(video_data.get('duration', {}).get('value'), 1000),
151             'age_limit': parse_age_limit(video_data.get('tvrating', {}).get('rating')),
152             'episode_number': int_or_none(video_data.get('episodenumber')),
153             'series': video_data.get('show', {}).get('title'),
154             'season_number': int_or_none(video_data.get('season', {}).get('num')),
155             'thumbnails': thumbnails,
156             'formats': formats,
157             'subtitles': subtitles,
158         }