[theplatform] Add ThePlatformFeedIE
[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 ..utils import (
13     determine_ext,
14     ExtractorError,
15     xpath_with_ns,
16     unsmuggle_url,
17     int_or_none,
18     url_basename,
19     float_or_none,
20 )
21
22 default_ns = 'http://www.w3.org/2005/SMIL21/Language'
23 _x = lambda p: xpath_with_ns(p, {'smil': default_ns})
24
25
26 class ThePlatformBaseIE(InfoExtractor):
27     def _extract_theplatform_smil_formats(self, smil_url, video_id, note='Downloading SMIL data'):
28         meta = self._download_xml(smil_url, video_id, note=note)
29         try:
30             error_msg = next(
31                 n.attrib['abstract']
32                 for n in meta.findall(_x('.//smil:ref'))
33                 if n.attrib.get('title') == 'Geographic Restriction' or n.attrib.get('title') == 'Expired')
34         except StopIteration:
35             pass
36         else:
37             raise ExtractorError(error_msg, expected=True)
38
39         formats = self._parse_smil_formats(
40             meta, smil_url, video_id, namespace=default_ns,
41             # the parameters are from syfy.com, other sites may use others,
42             # they also work for nbc.com
43             f4m_params={'g': 'UXWGVKRWHFSP', 'hdcore': '3.0.3'},
44             transform_rtmp_url=lambda streamer, src: (streamer, 'mp4:' + src))
45
46         for _format in formats:
47             ext = determine_ext(_format['url'])
48             if ext == 'once':
49                 _format['ext'] = 'mp4'
50
51         self._sort_formats(formats)
52
53         return formats
54
55     def get_metadata(self, path, video_id):
56         info_url = 'http://link.theplatform.com/s/%s?format=preview' % path
57         info_json = self._download_webpage(info_url, video_id)
58         info = json.loads(info_json)
59
60         subtitles = {}
61         captions = info.get('captions')
62         if isinstance(captions, list):
63             for caption in captions:
64                 lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
65                 subtitles[lang] = [{
66                     'ext': 'srt' if mime == 'text/srt' else 'ttml',
67                     'url': src,
68                 }]
69
70         return {
71             'title': info['title'],
72             'subtitles': subtitles,
73             'description': info['description'],
74             'thumbnail': info['defaultThumbnailUrl'],
75             'duration': int_or_none(info.get('duration'), 1000),
76         }
77
78
79 class ThePlatformIE(ThePlatformBaseIE):
80     _VALID_URL = r'''(?x)
81         (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
82            (?:(?P<media>(?:[^/]+/)+select/media/)|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
83          |theplatform:)(?P<id>[^/\?&]+)'''
84
85     _TESTS = [{
86         # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
87         'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
88         'info_dict': {
89             'id': 'e9I_cZgTgIPd',
90             'ext': 'flv',
91             'title': 'Blackberry\'s big, bold Z30',
92             'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
93             'duration': 247,
94         },
95         'params': {
96             # rtmp download
97             'skip_download': True,
98         },
99     }, {
100         # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
101         'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
102         'info_dict': {
103             'id': '22d_qsQ6MIRT',
104             'ext': 'flv',
105             'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
106             'title': 'Tesla Model S: A second step towards a cleaner motoring future',
107         },
108         'params': {
109             # rtmp download
110             'skip_download': True,
111         }
112     }, {
113         'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
114         'info_dict': {
115             'id': 'yMBg9E8KFxZD',
116             'ext': 'mp4',
117             'description': 'md5:644ad9188d655b742f942bf2e06b002d',
118             'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
119         }
120     }, {
121         'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
122         'only_matching': True,
123     }]
124
125     @staticmethod
126     def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
127         flags = '10' if include_qs else '00'
128         expiration_date = '%x' % (int(time.time()) + life)
129
130         def str_to_hex(str):
131             return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
132
133         def hex_to_str(hex):
134             return binascii.a2b_hex(hex)
135
136         relative_path = url.split('http://link.theplatform.com/s/')[1].split('?')[0]
137         clear_text = hex_to_str(flags + expiration_date + str_to_hex(relative_path))
138         checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
139         sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
140         return '%s&sig=%s' % (url, sig)
141
142     def _real_extract(self, url):
143         url, smuggled_data = unsmuggle_url(url, {})
144
145         mobj = re.match(self._VALID_URL, url)
146         provider_id = mobj.group('provider_id')
147         video_id = mobj.group('id')
148
149         if not provider_id:
150             provider_id = 'dJ5BDC'
151
152         path = provider_id
153         if mobj.group('media'):
154             path += '/media'
155         path += '/' + video_id
156
157         if smuggled_data.get('force_smil_url', False):
158             smil_url = url
159         elif mobj.group('config'):
160             config_url = url + '&form=json'
161             config_url = config_url.replace('swf/', 'config/')
162             config_url = config_url.replace('onsite/', 'onsite/config/')
163             config = self._download_json(config_url, video_id, 'Downloading config')
164             if 'releaseUrl' in config:
165                 release_url = config['releaseUrl']
166             else:
167                 release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
168             smil_url = release_url + '&format=SMIL&formats=MPEG4&manifest=f4m'
169         else:
170             smil_url = 'http://link.theplatform.com/s/%s/meta.smil?format=smil&mbr=true' % path
171
172         sig = smuggled_data.get('sig')
173         if sig:
174             smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
175
176         formats = self._extract_theplatform_smil_formats(smil_url, video_id)
177
178         ret = self.get_metadata(path, video_id)
179         ret.update({
180             'id': video_id,
181             'formats': formats,
182         })
183
184         return ret
185
186
187 class ThePlatformFeedIE(ThePlatformBaseIE):
188     _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&byGuid=%s'
189     _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*byGuid=(?P<id>[a-zA-Z0-9_]+)'
190     _TEST = {
191         # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
192         'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
193         'md5': '22d2b84f058d3586efcd99e57d59d314',
194         'info_dict': {
195             'id': 'n_hardball_5biden_140207',
196             'ext': 'mp4',
197             'title': 'The Biden factor: will Joe run in 2016?',
198             'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
199             'thumbnail': 're:^https?://.*\.jpg$',
200             'upload_date': '20140208',
201             'timestamp': 1391824260,
202             'duration': 467.0,
203             'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
204         },
205     }
206
207     def _real_extract(self, url):
208         mobj = re.match(self._VALID_URL, url)
209
210         video_id = mobj.group('id')
211         provider_id = mobj.group('provider_id')
212         feed_id = mobj.group('feed_id')
213
214         real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, video_id)
215         feed = self._download_json(real_url, video_id)
216         entry = feed['entries'][0]
217
218         formats = []
219         first_video_id = None
220         duration = None
221         for item in entry['media$content']:
222             smil_url = item['plfile$url'] + '&format=SMIL&Tracking=true&Embedded=true&formats=MPEG4,F4M'
223             cur_video_id = url_basename(smil_url)
224             if first_video_id is None:
225                 first_video_id = cur_video_id
226                 duration = float_or_none(item.get('plfile$duration'))
227             formats.extend(self._extract_theplatform_smil_formats(smil_url, video_id, 'Downloading SMIL data for %s' % cur_video_id))
228
229         self._sort_formats(formats)
230
231         thumbnails = [{
232             'url': thumbnail['plfile$url'],
233             'width': int_or_none(thumbnail.get('plfile$width')),
234             'height': int_or_none(thumbnail.get('plfile$height')),
235         } for thumbnail in entry.get('media$thumbnails', [])]
236
237         timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
238         categories = [item['media$name'] for item in entry.get('media$categories', [])]
239
240         ret = self.get_metadata('%s/%s' % (provider_id, first_video_id), video_id)
241         ret.update({
242             'id': video_id,
243             'formats': formats,
244             'thumbnails': thumbnails,
245             'duration': duration,
246             'timestamp': timestamp,
247             'categories': categories,
248         })
249
250         return ret