[go] Add support for abc.com and freeform.com (closes #22823, closes #22864)
[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             'resource_id': 'Disney',
29         },
30         'watchdisneyjunior': {
31             'brand': '008',
32             'resource_id': 'DisneyJunior',
33         },
34         'watchdisneyxd': {
35             'brand': '009',
36             'resource_id': 'DisneyXD',
37         },
38         'disneynow': {
39             'brand': '011',
40             'resource_id': 'Disney',
41         }
42     }
43     _VALID_URL = r'https?://(?:(?:(?P<sub_domain>%s)\.)?go|(?P<sub_domain_2>abc|freeform|disneynow))\.com/(?:(?:[^/]+/)*(?P<id>vdka\w+)|(?:[^/]+/)*(?P<display_id>[^/?#]+))'\
44                  % '|'.join(list(_SITE_INFO.keys()))
45     _TESTS = [{
46         'url': 'http://abc.go.com/shows/designated-survivor/video/most-recent/VDKA3807643',
47         'info_dict': {
48             'id': 'VDKA3807643',
49             'ext': 'mp4',
50             'title': 'The Traitor in the White House',
51             'description': 'md5:05b009d2d145a1e85d25111bd37222e8',
52         },
53         'params': {
54             # m3u8 download
55             'skip_download': True,
56         },
57         'skip': 'This content is no longer available.',
58     }, {
59         'url': 'http://watchdisneyxd.go.com/doraemon',
60         'info_dict': {
61             'title': 'Doraemon',
62             'id': 'SH55574025',
63         },
64         'playlist_mincount': 51,
65     }, {
66         'url': 'http://freeform.go.com/shows/shadowhunters/episodes/season-2/1-this-guilty-blood',
67         'info_dict': {
68             'id': 'VDKA3609139',
69             'ext': 'mp4',
70             'title': 'This Guilty Blood',
71             'description': 'md5:f18e79ad1c613798d95fdabfe96cd292',
72             'age_limit': 14,
73         },
74         'params': {
75             'geo_bypass_ip_block': '3.244.239.0/24',
76             # m3u8 download
77             'skip_download': True,
78         },
79     }, {
80         'url': 'https://abc.com/shows/the-rookie/episode-guide/season-02/03-the-bet',
81         'info_dict': {
82             'id': 'VDKA13435179',
83             'ext': 'mp4',
84             'title': 'The Bet',
85             'description': 'md5:c66de8ba2e92c6c5c113c3ade84ab404',
86             'age_limit': 14,
87         },
88         'params': {
89             'geo_bypass_ip_block': '3.244.239.0/24',
90             # m3u8 download
91             'skip_download': True,
92         },
93     }, {
94         'url': 'http://abc.go.com/shows/the-catch/episode-guide/season-01/10-the-wedding',
95         'only_matching': True,
96     }, {
97         'url': 'http://abc.go.com/shows/world-news-tonight/episode-guide/2017-02/17-021717-intense-stand-off-between-man-with-rifle-and-police-in-oakland',
98         'only_matching': True,
99     }, {
100         # brand 004
101         'url': 'http://disneynow.go.com/shows/big-hero-6-the-series/season-01/episode-10-mr-sparkles-loses-his-sparkle/vdka4637915',
102         'only_matching': True,
103     }, {
104         # brand 008
105         'url': 'http://disneynow.go.com/shows/minnies-bow-toons/video/happy-campers/vdka4872013',
106         'only_matching': True,
107     }, {
108         'url': 'https://disneynow.com/shows/minnies-bow-toons/video/happy-campers/vdka4872013',
109         'only_matching': True,
110     }]
111
112     def _extract_videos(self, brand, video_id='-1', show_id='-1'):
113         display_id = video_id if video_id != '-1' else show_id
114         return self._download_json(
115             'http://api.contents.watchabc.go.com/vp2/ws/contents/3000/videos/%s/001/-1/%s/-1/%s/-1/-1.json' % (brand, show_id, video_id),
116             display_id)['video']
117
118     def _real_extract(self, url):
119         mobj = re.match(self._VALID_URL, url)
120         sub_domain = mobj.group('sub_domain') or mobj.group('sub_domain_2')
121         video_id, display_id = mobj.group('id', 'display_id')
122         site_info = self._SITE_INFO.get(sub_domain, {})
123         brand = site_info.get('brand')
124         if not video_id or not site_info:
125             webpage = self._download_webpage(url, display_id or video_id)
126             video_id = self._search_regex(
127                 (
128                     # There may be inner quotes, e.g. data-video-id="'VDKA3609139'"
129                     # from http://freeform.go.com/shows/shadowhunters/episodes/season-2/1-this-guilty-blood
130                     r'data-video-id=["\']*(VDKA\w+)',
131                     # https://abc.com/shows/the-rookie/episode-guide/season-02/03-the-bet
132                     r'\b(?:video)?id["\']\s*:\s*["\'](VDKA\w+)'
133                 ), webpage, 'video id', default=video_id)
134             if not site_info:
135                 brand = self._search_regex(
136                     (r'data-brand=\s*["\']\s*(\d+)',
137                      r'data-page-brand=\s*["\']\s*(\d+)'), webpage, 'brand',
138                     default='004')
139                 site_info = next(
140                     si for _, si in self._SITE_INFO.items()
141                     if si.get('brand') == brand)
142             if not video_id:
143                 # show extraction works for Disney, DisneyJunior and DisneyXD
144                 # ABC and Freeform has different layout
145                 show_id = self._search_regex(r'data-show-id=["\']*(SH\d+)', webpage, 'show id')
146                 videos = self._extract_videos(brand, show_id=show_id)
147                 show_title = self._search_regex(r'data-show-title="([^"]+)"', webpage, 'show title', fatal=False)
148                 entries = []
149                 for video in videos:
150                     entries.append(self.url_result(
151                         video['url'], 'Go', video.get('id'), video.get('title')))
152                 entries.reverse()
153                 return self.playlist_result(entries, show_id, show_title)
154         video_data = self._extract_videos(brand, video_id)[0]
155         video_id = video_data['id']
156         title = video_data['title']
157
158         formats = []
159         for asset in video_data.get('assets', {}).get('asset', []):
160             asset_url = asset.get('value')
161             if not asset_url:
162                 continue
163             format_id = asset.get('format')
164             ext = determine_ext(asset_url)
165             if ext == 'm3u8':
166                 video_type = video_data.get('type')
167                 data = {
168                     'video_id': video_data['id'],
169                     'video_type': video_type,
170                     'brand': brand,
171                     'device': '001',
172                 }
173                 if video_data.get('accesslevel') == '1':
174                     requestor_id = site_info.get('requestor_id', 'DisneyChannels')
175                     resource = site_info.get('resource_id') or self._get_mvpd_resource(
176                         requestor_id, title, video_id, None)
177                     auth = self._extract_mvpd_auth(
178                         url, video_id, requestor_id, resource)
179                     data.update({
180                         'token': auth,
181                         'token_type': 'ap',
182                         'adobe_requestor_id': requestor_id,
183                     })
184                 else:
185                     self._initialize_geo_bypass({'countries': ['US']})
186                 entitlement = self._download_json(
187                     'https://api.entitlement.watchabc.go.com/vp2/ws-secure/entitlement/2020/authorize.json',
188                     video_id, data=urlencode_postdata(data))
189                 errors = entitlement.get('errors', {}).get('errors', [])
190                 if errors:
191                     for error in errors:
192                         if error.get('code') == 1002:
193                             self.raise_geo_restricted(
194                                 error['message'], countries=['US'])
195                     error_message = ', '.join([error['message'] for error in errors])
196                     raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
197                 asset_url += '?' + entitlement['uplynkData']['sessionKey']
198                 formats.extend(self._extract_m3u8_formats(
199                     asset_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False))
200             else:
201                 f = {
202                     'format_id': format_id,
203                     'url': asset_url,
204                     'ext': ext,
205                 }
206                 if re.search(r'(?:/mp4/source/|_source\.mp4)', asset_url):
207                     f.update({
208                         'format_id': ('%s-' % format_id if format_id else '') + 'SOURCE',
209                         'preference': 1,
210                     })
211                 else:
212                     mobj = re.search(r'/(\d+)x(\d+)/', asset_url)
213                     if mobj:
214                         height = int(mobj.group(2))
215                         f.update({
216                             'format_id': ('%s-' % format_id if format_id else '') + '%dP' % height,
217                             'width': int(mobj.group(1)),
218                             'height': height,
219                         })
220                 formats.append(f)
221         self._sort_formats(formats)
222
223         subtitles = {}
224         for cc in video_data.get('closedcaption', {}).get('src', []):
225             cc_url = cc.get('value')
226             if not cc_url:
227                 continue
228             ext = determine_ext(cc_url)
229             if ext == 'xml':
230                 ext = 'ttml'
231             subtitles.setdefault(cc.get('lang'), []).append({
232                 'url': cc_url,
233                 'ext': ext,
234             })
235
236         thumbnails = []
237         for thumbnail in video_data.get('thumbnails', {}).get('thumbnail', []):
238             thumbnail_url = thumbnail.get('value')
239             if not thumbnail_url:
240                 continue
241             thumbnails.append({
242                 'url': thumbnail_url,
243                 'width': int_or_none(thumbnail.get('width')),
244                 'height': int_or_none(thumbnail.get('height')),
245             })
246
247         return {
248             'id': video_id,
249             'title': title,
250             'description': video_data.get('longdescription') or video_data.get('description'),
251             'duration': int_or_none(video_data.get('duration', {}).get('value'), 1000),
252             'age_limit': parse_age_limit(video_data.get('tvrating', {}).get('rating')),
253             'episode_number': int_or_none(video_data.get('episodenumber')),
254             'series': video_data.get('show', {}).get('title'),
255             'season_number': int_or_none(video_data.get('season', {}).get('num')),
256             'thumbnails': thumbnails,
257             'formats': formats,
258             'subtitles': subtitles,
259         }