[shahid] add default fallbacks for extracting api vars
[youtube-dl] / youtube_dl / extractor / theplatform.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5 import time
6 import hmac
7 import binascii
8 import hashlib
9
10
11 from .common import InfoExtractor
12 from ..compat import (
13     compat_str,
14 )
15 from ..utils import (
16     determine_ext,
17     ExtractorError,
18     xpath_with_ns,
19     unsmuggle_url,
20     int_or_none,
21 )
22
23 _x = lambda p: xpath_with_ns(p, {'smil': 'http://www.w3.org/2005/SMIL21/Language'})
24
25
26 class ThePlatformIE(InfoExtractor):
27     _VALID_URL = r'''(?x)
28         (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
29            (?:(?P<media>(?:[^/]+/)+select/media/)|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
30          |theplatform:)(?P<id>[^/\?&]+)'''
31
32     _TESTS = [{
33         # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
34         'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
35         'info_dict': {
36             'id': 'e9I_cZgTgIPd',
37             'ext': 'flv',
38             'title': 'Blackberry\'s big, bold Z30',
39             'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
40             'duration': 247,
41         },
42         'params': {
43             # rtmp download
44             'skip_download': True,
45         },
46     }, {
47         # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
48         'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
49         'info_dict': {
50             'id': '22d_qsQ6MIRT',
51             'ext': 'flv',
52             'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
53             'title': 'Tesla Model S: A second step towards a cleaner motoring future',
54         },
55         'params': {
56             # rtmp download
57             'skip_download': True,
58         }
59     }, {
60         'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
61         'info_dict': {
62             'id': 'yMBg9E8KFxZD',
63             'ext': 'mp4',
64             'description': 'md5:644ad9188d655b742f942bf2e06b002d',
65             'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
66         }
67     }, {
68         'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
69         'only_matching': True,
70     }]
71
72     @staticmethod
73     def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
74         flags = '10' if include_qs else '00'
75         expiration_date = '%x' % (int(time.time()) + life)
76
77         def str_to_hex(str):
78             return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
79
80         def hex_to_str(hex):
81             return binascii.a2b_hex(hex)
82
83         relative_path = url.split('http://link.theplatform.com/s/')[1].split('?')[0]
84         clear_text = hex_to_str(flags + expiration_date + str_to_hex(relative_path))
85         checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
86         sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
87         return '%s&sig=%s' % (url, sig)
88
89     def _real_extract(self, url):
90         url, smuggled_data = unsmuggle_url(url, {})
91
92         mobj = re.match(self._VALID_URL, url)
93         provider_id = mobj.group('provider_id')
94         video_id = mobj.group('id')
95
96         if not provider_id:
97             provider_id = 'dJ5BDC'
98
99         path = provider_id
100         if mobj.group('media'):
101             path += '/media'
102         path += '/' + video_id
103
104         if smuggled_data.get('force_smil_url', False):
105             smil_url = url
106         elif mobj.group('config'):
107             config_url = url + '&form=json'
108             config_url = config_url.replace('swf/', 'config/')
109             config_url = config_url.replace('onsite/', 'onsite/config/')
110             config = self._download_json(config_url, video_id, 'Downloading config')
111             smil_url = config['releaseUrl'] + '&format=SMIL&formats=MPEG4&manifest=f4m'
112         else:
113             smil_url = 'http://link.theplatform.com/s/%s/meta.smil?format=smil&mbr=true' % path
114
115         sig = smuggled_data.get('sig')
116         if sig:
117             smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
118
119         meta = self._download_xml(smil_url, video_id)
120         try:
121             error_msg = next(
122                 n.attrib['abstract']
123                 for n in meta.findall(_x('.//smil:ref'))
124                 if n.attrib.get('title') == 'Geographic Restriction' or n.attrib.get('title') == 'Expired')
125         except StopIteration:
126             pass
127         else:
128             raise ExtractorError(error_msg, expected=True)
129
130         info_url = 'http://link.theplatform.com/s/%s?format=preview' % path
131         info_json = self._download_webpage(info_url, video_id)
132         info = json.loads(info_json)
133
134         subtitles = {}
135         captions = info.get('captions')
136         if isinstance(captions, list):
137             for caption in captions:
138                 lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
139                 subtitles[lang] = [{
140                     'ext': 'srt' if mime == 'text/srt' else 'ttml',
141                     'url': src,
142                 }]
143
144         head = meta.find(_x('smil:head'))
145         body = meta.find(_x('smil:body'))
146
147         f4m_node = body.find(_x('smil:seq//smil:video'))
148         if f4m_node is None:
149             f4m_node = body.find(_x('smil:seq/smil:video'))
150         if f4m_node is not None and '.f4m' in f4m_node.attrib['src']:
151             f4m_url = f4m_node.attrib['src']
152             if 'manifest.f4m?' not in f4m_url:
153                 f4m_url += '?'
154             # the parameters are from syfy.com, other sites may use others,
155             # they also work for nbc.com
156             f4m_url += '&g=UXWGVKRWHFSP&hdcore=3.0.3'
157             formats = self._extract_f4m_formats(f4m_url, video_id)
158         else:
159             formats = []
160             switch = body.find(_x('smil:switch'))
161             if switch is None:
162                 switch = body.find(_x('smil:par//smil:switch'))
163             if switch is None:
164                 switch = body.find(_x('smil:par/smil:switch'))
165             if switch is None:
166                 switch = body.find(_x('smil:par'))
167             if switch is not None:
168                 base_url = head.find(_x('smil:meta')).attrib['base']
169                 for f in switch.findall(_x('smil:video')):
170                     attr = f.attrib
171                     width = int_or_none(attr.get('width'))
172                     height = int_or_none(attr.get('height'))
173                     vbr = int_or_none(attr.get('system-bitrate'), 1000)
174                     format_id = '%dx%d_%dk' % (width, height, vbr)
175                     formats.append({
176                         'format_id': format_id,
177                         'url': base_url,
178                         'play_path': 'mp4:' + attr['src'],
179                         'ext': 'flv',
180                         'width': width,
181                         'height': height,
182                         'vbr': vbr,
183                     })
184             else:
185                 switch = body.find(_x('smil:seq//smil:switch'))
186                 if switch is None:
187                     switch = body.find(_x('smil:seq/smil:switch'))
188                 for f in switch.findall(_x('smil:video')):
189                     attr = f.attrib
190                     vbr = int_or_none(attr.get('system-bitrate'), 1000)
191                     ext = determine_ext(attr['src'])
192                     if ext == 'once':
193                         ext = 'mp4'
194                     formats.append({
195                         'format_id': compat_str(vbr),
196                         'url': attr['src'],
197                         'vbr': vbr,
198                         'ext': ext,
199                     })
200             self._sort_formats(formats)
201
202         return {
203             'id': video_id,
204             'title': info['title'],
205             'subtitles': subtitles,
206             'formats': formats,
207             'description': info['description'],
208             'thumbnail': info['defaultThumbnailUrl'],
209             'duration': int_or_none(info.get('duration'), 1000),
210         }