[scrippsnetworks:watch] Fix extraction (closes #14389)
[ytdl] / youtube_dl / extractor / scrippsnetworks.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import datetime
5 import json
6 import hashlib
7 import hmac
8 import re
9
10 from .common import InfoExtractor
11 from .anvato import AnvatoIE
12 from ..utils import (
13     urlencode_postdata,
14     xpath_text,
15 )
16
17
18 class ScrippsNetworksWatchIE(InfoExtractor):
19     IE_NAME = 'scrippsnetworks:watch'
20     _VALID_URL = r'''(?x)
21                     https?://
22                         watch\.
23                         (?P<site>hgtv|foodnetwork|travelchannel|diynetwork|cookingchanneltv)\.com/
24                         (?:
25                             player\.[A-Z0-9]+\.html\#|
26                             show/(?:[^/]+/){2}
27                         )
28                         (?P<id>\d+)
29                     '''
30     _TESTS = [{
31         'url': 'http://watch.hgtv.com/show/HGTVE/Best-Ever-Treehouses/2241515/Best-Ever-Treehouses/',
32         'md5': '26545fd676d939954c6808274bdb905a',
33         'info_dict': {
34             'id': '4173834',
35             'ext': 'mp4',
36             'title': 'Best Ever Treehouses',
37             'description': "We're searching for the most over the top treehouses.",
38             'uploader': 'ANV',
39             'upload_date': '20170922',
40             'timestamp': 1506056400,
41         },
42         'params': {
43             'skip_download': True,
44         },
45         'add_ie': [AnvatoIE.ie_key()],
46     }, {
47         'url': 'http://watch.diynetwork.com/show/DSAL/Salvage-Dawgs/2656646/Covington-Church/',
48         'only_matching': True,
49     }, {
50         'url': 'http://watch.diynetwork.com/player.HNT.html#2656646',
51         'only_matching': True,
52     }]
53
54     _SNI_TABLE = {
55         'hgtv': 'hgtv',
56         'diynetwork': 'diy',
57         'foodnetwork': 'food',
58         'cookingchanneltv': 'cook',
59         'travelchannel': 'trav',
60         'geniuskitchen': 'geniuskitchen',
61     }
62     _SNI_HOST = 'web.api.video.snidigital.com'
63
64     _AWS_REGION = 'us-east-1'
65     _AWS_IDENTITY_ID_JSON = json.dumps({
66         'IdentityId': '%s:7655847c-0ae7-4d9b-80d6-56c062927eb3' % _AWS_REGION
67     })
68     _AWS_USER_AGENT = 'aws-sdk-js/2.80.0 callback'
69     _AWS_API_KEY = 'E7wSQmq0qK6xPrF13WmzKiHo4BQ7tip4pQcSXVl1'
70     _AWS_SERVICE = 'execute-api'
71     _AWS_REQUEST = 'aws4_request'
72     _AWS_SIGNED_HEADERS = ';'.join([
73         'host', 'x-amz-date', 'x-amz-security-token', 'x-api-key'])
74     _AWS_CANONICAL_REQUEST_TEMPLATE = '''GET
75 %(uri)s
76
77 host:%(host)s
78 x-amz-date:%(date)s
79 x-amz-security-token:%(token)s
80 x-api-key:%(key)s
81
82 %(signed_headers)s
83 %(payload_hash)s'''
84
85     def _real_extract(self, url):
86         mobj = re.match(self._VALID_URL, url)
87         site_id, video_id = mobj.group('site', 'id')
88
89         def aws_hash(s):
90             return hashlib.sha256(s.encode('utf-8')).hexdigest()
91
92         token = self._download_json(
93             'https://cognito-identity.us-east-1.amazonaws.com/', video_id,
94             data=self._AWS_IDENTITY_ID_JSON.encode('utf-8'),
95             headers={
96                 'Accept': '*/*',
97                 'Content-Type': 'application/x-amz-json-1.1',
98                 'Referer': url,
99                 'X-Amz-Content-Sha256': aws_hash(self._AWS_IDENTITY_ID_JSON),
100                 'X-Amz-Target': 'AWSCognitoIdentityService.GetOpenIdToken',
101                 'X-Amz-User-Agent': self._AWS_USER_AGENT,
102             })['Token']
103
104         sts = self._download_xml(
105             'https://sts.amazonaws.com/', video_id, data=urlencode_postdata({
106                 'Action': 'AssumeRoleWithWebIdentity',
107                 'RoleArn': 'arn:aws:iam::710330595350:role/Cognito_WebAPIUnauth_Role',
108                 'RoleSessionName': 'web-identity',
109                 'Version': '2011-06-15',
110                 'WebIdentityToken': token,
111             }), headers={
112                 'Referer': url,
113                 'X-Amz-User-Agent': self._AWS_USER_AGENT,
114                 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
115             })
116
117         def get(key):
118             return xpath_text(
119                 sts, './/{https://sts.amazonaws.com/doc/2011-06-15/}%s' % key,
120                 fatal=True)
121
122         access_key_id = get('AccessKeyId')
123         secret_access_key = get('SecretAccessKey')
124         session_token = get('SessionToken')
125
126         # Task 1: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
127         uri = '/1/web/brands/%s/episodes/scrid/%s' % (self._SNI_TABLE[site_id], video_id)
128         datetime_now = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
129         date = datetime_now[:8]
130         canonical_string = self._AWS_CANONICAL_REQUEST_TEMPLATE % {
131             'uri': uri,
132             'host': self._SNI_HOST,
133             'date': datetime_now,
134             'token': session_token,
135             'key': self._AWS_API_KEY,
136             'signed_headers': self._AWS_SIGNED_HEADERS,
137             'payload_hash': aws_hash(''),
138         }
139
140         # Task 2: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
141         credential_string = '/'.join([date, self._AWS_REGION, self._AWS_SERVICE, self._AWS_REQUEST])
142         string_to_sign = '\n'.join([
143             'AWS4-HMAC-SHA256', datetime_now, credential_string,
144             aws_hash(canonical_string)])
145
146         # Task 3: http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
147         def aws_hmac(key, msg):
148             return hmac.new(key, msg.encode('utf-8'), hashlib.sha256)
149
150         def aws_hmac_digest(key, msg):
151             return aws_hmac(key, msg).digest()
152
153         def aws_hmac_hexdigest(key, msg):
154             return aws_hmac(key, msg).hexdigest()
155
156         k_secret = 'AWS4' + secret_access_key
157         k_date = aws_hmac_digest(k_secret.encode('utf-8'), date)
158         k_region = aws_hmac_digest(k_date, self._AWS_REGION)
159         k_service = aws_hmac_digest(k_region, self._AWS_SERVICE)
160         k_signing = aws_hmac_digest(k_service, self._AWS_REQUEST)
161
162         signature = aws_hmac_hexdigest(k_signing, string_to_sign)
163
164         auth_header = ', '.join([
165             'AWS4-HMAC-SHA256 Credential=%s' % '/'.join(
166                 [access_key_id, date, self._AWS_REGION, self._AWS_SERVICE, self._AWS_REQUEST]),
167             'SignedHeaders=%s' % self._AWS_SIGNED_HEADERS,
168             'Signature=%s' % signature,
169         ])
170
171         mcp_id = self._download_json(
172             'https://%s%s' % (self._SNI_HOST, uri), video_id, headers={
173                 'Accept': '*/*',
174                 'Referer': url,
175                 'Authorization': auth_header,
176                 'X-Amz-Date': datetime_now,
177                 'X-Amz-Security-Token': session_token,
178                 'X-Api-Key': self._AWS_API_KEY,
179             })['results'][0]['mcpId']
180
181         return self.url_result(
182             'anvato:anvato_scripps_app_web_prod_0837996dbe373629133857ae9eb72e740424d80a:%s' % mcp_id,
183             AnvatoIE.ie_key(), video_id=mcp_id)