[discovery] use API call for video data extraction(#21808)
[youtube-dl] / youtube_dl / extractor / discovery.py
1 from __future__ import unicode_literals
2
3 import random
4 import re
5 import string
6
7 from .discoverygo import DiscoveryGoBaseIE
8 from ..compat import compat_urllib_parse_unquote
9 from ..utils import ExtractorError
10 from ..compat import compat_HTTPError
11
12
13 class DiscoveryIE(DiscoveryGoBaseIE):
14     _VALID_URL = r'''(?x)https?://
15         (?P<site>
16             (?:(?:www|go)\.)?discovery|
17             (?:www\.)?
18                 (?:
19                     investigationdiscovery|
20                     discoverylife|
21                     animalplanet|
22                     ahctv|
23                     destinationamerica|
24                     sciencechannel|
25                     tlc|
26                     velocity
27                 )|
28             watch\.
29                 (?:
30                     hgtv|
31                     foodnetwork|
32                     travelchannel|
33                     diynetwork|
34                     cookingchanneltv|
35                     motortrend
36                 )
37         )\.com/tv-shows/[^/]+/(?:video|full-episode)s/(?P<id>[^./?#]+)'''
38     _TESTS = [{
39         'url': 'https://go.discovery.com/tv-shows/cash-cab/videos/riding-with-matthew-perry',
40         'info_dict': {
41             'id': '5a2f35ce6b66d17a5026e29e',
42             'ext': 'mp4',
43             'title': 'Riding with Matthew Perry',
44             'description': 'md5:a34333153e79bc4526019a5129e7f878',
45             'duration': 84,
46         },
47         'params': {
48             'skip_download': True,  # requires ffmpeg
49         }
50     }, {
51         'url': 'https://www.investigationdiscovery.com/tv-shows/final-vision/full-episodes/final-vision',
52         'only_matching': True,
53     }, {
54         'url': 'https://go.discovery.com/tv-shows/alaskan-bush-people/videos/follow-your-own-road',
55         'only_matching': True,
56     }]
57     _GEO_COUNTRIES = ['US']
58     _GEO_BYPASS = False
59     _API_BASE_URL = 'https://api.discovery.com/v1/'
60
61     def _real_extract(self, url):
62         site, display_id = re.match(self._VALID_URL, url).groups()
63
64         access_token = None
65         cookies = self._get_cookies(url)
66
67         # prefer Affiliate Auth Token over Anonymous Auth Token
68         auth_storage_cookie = cookies.get('eosAf') or cookies.get('eosAn')
69         if auth_storage_cookie and auth_storage_cookie.value:
70             auth_storage = self._parse_json(compat_urllib_parse_unquote(
71                 compat_urllib_parse_unquote(auth_storage_cookie.value)),
72                 display_id, fatal=False) or {}
73             access_token = auth_storage.get('a') or auth_storage.get('access_token')
74
75         if not access_token:
76             access_token = self._download_json(
77                 'https://%s.com/anonymous' % site, display_id,
78                 'Downloading token JSON metadata', query={
79                     'authRel': 'authorization',
80                     'client_id': '3020a40c2356a645b4b4',
81                     'nonce': ''.join([random.choice(string.ascii_letters) for _ in range(32)]),
82                     'redirectUri': 'https://fusion.ddmcdn.com/app/mercury-sdk/180/redirectHandler.html?https://www.%s.com' % site,
83                 })['access_token']
84
85         headers = self.geo_verification_headers()
86         headers['Authorization'] = 'Bearer ' + access_token
87
88         try:
89             video = self._download_json(
90                 self._API_BASE_URL + 'content/videos',
91                 display_id, 'Downloading content JSON metadata',
92                 headers=headers, query={
93                     'slug': display_id,
94                 })[0]
95             video_id = video['id']
96             stream = self._download_json(
97                 self._API_BASE_URL + 'streaming/video/' + video_id,
98                 display_id, 'Downloading streaming JSON metadata', headers=headers)
99         except ExtractorError as e:
100             if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403):
101                 e_description = self._parse_json(
102                     e.cause.read().decode(), display_id)['description']
103                 if 'resource not available for country' in e_description:
104                     self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
105                 if 'Authorized Networks' in e_description:
106                     raise ExtractorError(
107                         'This video is only available via cable service provider subscription that'
108                         ' is not currently supported. You may want to use --cookies.', expected=True)
109                 raise ExtractorError(e_description)
110             raise
111
112         return self._extract_video_info(video, stream, display_id)