Merge branch 'shahid' of https://github.com/remitamine/youtube-dl into remitamine...
[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             if 'releaseUrl' in config:
112                 release_url = config['releaseUrl']
113             else:
114                 release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
115             smil_url = release_url + '&format=SMIL&formats=MPEG4&manifest=f4m'
116         else:
117             smil_url = 'http://link.theplatform.com/s/%s/meta.smil?format=smil&mbr=true' % path
118
119         sig = smuggled_data.get('sig')
120         if sig:
121             smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
122
123         meta = self._download_xml(smil_url, video_id)
124         try:
125             error_msg = next(
126                 n.attrib['abstract']
127                 for n in meta.findall(_x('.//smil:ref'))
128                 if n.attrib.get('title') == 'Geographic Restriction' or n.attrib.get('title') == 'Expired')
129         except StopIteration:
130             pass
131         else:
132             raise ExtractorError(error_msg, expected=True)
133
134         info_url = 'http://link.theplatform.com/s/%s?format=preview' % path
135         info_json = self._download_webpage(info_url, video_id)
136         info = json.loads(info_json)
137
138         subtitles = {}
139         captions = info.get('captions')
140         if isinstance(captions, list):
141             for caption in captions:
142                 lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
143                 subtitles[lang] = [{
144                     'ext': 'srt' if mime == 'text/srt' else 'ttml',
145                     'url': src,
146                 }]
147
148         head = meta.find(_x('smil:head'))
149         body = meta.find(_x('smil:body'))
150
151         f4m_node = body.find(_x('smil:seq//smil:video'))
152         if f4m_node is None:
153             f4m_node = body.find(_x('smil:seq/smil:video'))
154         if f4m_node is not None and '.f4m' in f4m_node.attrib['src']:
155             f4m_url = f4m_node.attrib['src']
156             if 'manifest.f4m?' not in f4m_url:
157                 f4m_url += '?'
158             # the parameters are from syfy.com, other sites may use others,
159             # they also work for nbc.com
160             f4m_url += '&g=UXWGVKRWHFSP&hdcore=3.0.3'
161             formats = self._extract_f4m_formats(f4m_url, video_id)
162         else:
163             formats = []
164             switch = body.find(_x('smil:switch'))
165             if switch is None:
166                 switch = body.find(_x('smil:par//smil:switch'))
167             if switch is None:
168                 switch = body.find(_x('smil:par/smil:switch'))
169             if switch is None:
170                 switch = body.find(_x('smil:par'))
171             if switch is not None:
172                 base_url = head.find(_x('smil:meta')).attrib['base']
173                 for f in switch.findall(_x('smil:video')):
174                     attr = f.attrib
175                     width = int_or_none(attr.get('width'))
176                     height = int_or_none(attr.get('height'))
177                     vbr = int_or_none(attr.get('system-bitrate'), 1000)
178                     format_id = '%dx%d_%dk' % (width, height, vbr)
179                     formats.append({
180                         'format_id': format_id,
181                         'url': base_url,
182                         'play_path': 'mp4:' + attr['src'],
183                         'ext': 'flv',
184                         'width': width,
185                         'height': height,
186                         'vbr': vbr,
187                     })
188             else:
189                 switch = body.find(_x('smil:seq//smil:switch'))
190                 if switch is None:
191                     switch = body.find(_x('smil:seq/smil:switch'))
192                 for f in switch.findall(_x('smil:video')):
193                     attr = f.attrib
194                     vbr = int_or_none(attr.get('system-bitrate'), 1000)
195                     ext = determine_ext(attr['src'])
196                     if ext == 'once':
197                         ext = 'mp4'
198                     formats.append({
199                         'format_id': compat_str(vbr),
200                         'url': attr['src'],
201                         'vbr': vbr,
202                         'ext': ext,
203                     })
204             self._sort_formats(formats)
205
206         return {
207             'id': video_id,
208             'title': info['title'],
209             'subtitles': subtitles,
210             'formats': formats,
211             'description': info['description'],
212             'thumbnail': info['defaultThumbnailUrl'],
213             'duration': int_or_none(info.get('duration'), 1000),
214         }