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