1579822f2c8611d6b9e8e464624321009d897251
[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 .subtitles import SubtitlesInfoExtractor
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(SubtitlesInfoExtractor):
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     _TEST = {
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
47     @staticmethod
48     def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
49         flags = '10' if include_qs else '00'
50         expiration_date = '%x' % (int(time.time()) + life)
51
52         def str_to_hex(str):
53             return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
54
55         def hex_to_str(hex):
56             return binascii.a2b_hex(hex)
57
58         relative_path = url.split('http://link.theplatform.com/s/')[1].split('?')[0]
59         clear_text = hex_to_str(flags + expiration_date + str_to_hex(relative_path))
60         checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
61         sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
62         return '%s&sig=%s' % (url, sig)
63
64     def _real_extract(self, url):
65         url, smuggled_data = unsmuggle_url(url, {})
66
67         mobj = re.match(self._VALID_URL, url)
68         provider_id = mobj.group('provider_id')
69         video_id = mobj.group('id')
70
71         if not provider_id:
72             provider_id = 'dJ5BDC'
73
74         if mobj.group('config'):
75             config_url = url + '&form=json'
76             config_url = config_url.replace('swf/', 'config/')
77             config_url = config_url.replace('onsite/', 'onsite/config/')
78             config = self._download_json(config_url, video_id, 'Downloading config')
79             smil_url = config['releaseUrl'] + '&format=SMIL&formats=MPEG4&manifest=f4m'
80         else:
81             smil_url = ('http://link.theplatform.com/s/{0}/{1}/meta.smil?'
82                         'format=smil&mbr=true'.format(provider_id, video_id))
83
84         sig = smuggled_data.get('sig')
85         if sig:
86             smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
87
88         meta = self._download_xml(smil_url, video_id)
89         try:
90             error_msg = next(
91                 n.attrib['abstract']
92                 for n in meta.findall(_x('.//smil:ref'))
93                 if n.attrib.get('title') == 'Geographic Restriction')
94         except StopIteration:
95             pass
96         else:
97             raise ExtractorError(error_msg, expected=True)
98
99         info_url = 'http://link.theplatform.com/s/{0}/{1}?format=preview'.format(provider_id, video_id)
100         info_json = self._download_webpage(info_url, video_id)
101         info = json.loads(info_json)
102
103         subtitles = {}
104         captions = info.get('captions')
105         if isinstance(captions, list):
106             for caption in captions:
107                 lang, src = caption.get('lang'), caption.get('src')
108                 if lang and src:
109                     subtitles[lang] = src
110
111         if self._downloader.params.get('listsubtitles', False):
112             self._list_available_subtitles(video_id, subtitles)
113             return
114
115         subtitles = self.extract_subtitles(video_id, subtitles)
116
117         head = meta.find(_x('smil:head'))
118         body = meta.find(_x('smil:body'))
119
120         f4m_node = body.find(_x('smil:seq//smil:video'))
121         if f4m_node is not None and '.f4m' in f4m_node.attrib['src']:
122             f4m_url = f4m_node.attrib['src']
123             if 'manifest.f4m?' not in f4m_url:
124                 f4m_url += '?'
125             # the parameters are from syfy.com, other sites may use others,
126             # they also work for nbc.com
127             f4m_url += '&g=UXWGVKRWHFSP&hdcore=3.0.3'
128             formats = self._extract_f4m_formats(f4m_url, video_id)
129         else:
130             formats = []
131             switch = body.find(_x('smil:switch'))
132             if switch is not None:
133                 base_url = head.find(_x('smil:meta')).attrib['base']
134                 for f in switch.findall(_x('smil:video')):
135                     attr = f.attrib
136                     width = int(attr['width'])
137                     height = int(attr['height'])
138                     vbr = int(attr['system-bitrate']) // 1000
139                     format_id = '%dx%d_%dk' % (width, height, vbr)
140                     formats.append({
141                         'format_id': format_id,
142                         'url': base_url,
143                         'play_path': 'mp4:' + attr['src'],
144                         'ext': 'flv',
145                         'width': width,
146                         'height': height,
147                         'vbr': vbr,
148                     })
149             else:
150                 switch = body.find(_x('smil:seq//smil:switch'))
151                 for f in switch.findall(_x('smil:video')):
152                     attr = f.attrib
153                     vbr = int(attr['system-bitrate']) // 1000
154                     ext = determine_ext(attr['src'])
155                     if ext == 'once':
156                         ext = 'mp4'
157                     formats.append({
158                         'format_id': compat_str(vbr),
159                         'url': attr['src'],
160                         'vbr': vbr,
161                         'ext': ext,
162                     })
163             self._sort_formats(formats)
164
165         return {
166             'id': video_id,
167             'title': info['title'],
168             'subtitles': subtitles,
169             'formats': formats,
170             'description': info['description'],
171             'thumbnail': info['defaultThumbnailUrl'],
172             'duration': info['duration'] // 1000,
173         }