[limelight] add support referer protected videos
[youtube-dl] / youtube_dl / extractor / limelight.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     determine_ext,
9     float_or_none,
10     int_or_none,
11     unsmuggle_url,
12 )
13
14
15 class LimelightBaseIE(InfoExtractor):
16     _PLAYLIST_SERVICE_URL = 'http://production-ps.lvp.llnw.net/r/PlaylistService/%s/%s/%s'
17     _API_URL = 'http://api.video.limelight.com/rest/organizations/%s/%s/%s/%s.json'
18
19     def _call_playlist_service(self, item_id, method, fatal=True, referer=None):
20         headers = {}
21         if referer:
22             headers['Referer'] = referer
23         return self._download_json(
24             self._PLAYLIST_SERVICE_URL % (self._PLAYLIST_SERVICE_PATH, item_id, method),
25             item_id, 'Downloading PlaylistService %s JSON' % method, fatal=fatal, headers=headers)
26
27     def _call_api(self, organization_id, item_id, method):
28         return self._download_json(
29             self._API_URL % (organization_id, self._API_PATH, item_id, method),
30             item_id, 'Downloading API %s JSON' % method)
31
32     def _extract(self, item_id, pc_method, mobile_method, meta_method, referer=None):
33         pc = self._call_playlist_service(item_id, pc_method, referer=referer)
34         metadata = self._call_api(pc['orgId'], item_id, meta_method)
35         mobile = self._call_playlist_service(item_id, mobile_method, fatal=False, referer=referer)
36         return pc, mobile, metadata
37
38     def _extract_info(self, streams, mobile_urls, properties):
39         video_id = properties['media_id']
40         formats = []
41         urls = []
42         for stream in streams:
43             stream_url = stream.get('url')
44             if not stream_url or stream.get('drmProtected') or stream_url in urls:
45                 continue
46             urls.append(stream_url)
47             ext = determine_ext(stream_url)
48             if ext == 'f4m':
49                 formats.extend(self._extract_f4m_formats(
50                     stream_url, video_id, f4m_id='hds', fatal=False))
51             else:
52                 fmt = {
53                     'url': stream_url,
54                     'abr': float_or_none(stream.get('audioBitRate')),
55                     'vbr': float_or_none(stream.get('videoBitRate')),
56                     'fps': float_or_none(stream.get('videoFrameRate')),
57                     'width': int_or_none(stream.get('videoWidthInPixels')),
58                     'height': int_or_none(stream.get('videoHeightInPixels')),
59                     'ext': ext,
60                 }
61                 rtmp = re.search(r'^(?P<url>rtmpe?://(?P<host>[^/]+)/(?P<app>.+))/(?P<playpath>mp4:.+)$', stream_url)
62                 if rtmp:
63                     format_id = 'rtmp'
64                     if stream.get('videoBitRate'):
65                         format_id += '-%d' % int_or_none(stream['videoBitRate'])
66                     http_format_id = format_id.replace('rtmp', 'http')
67
68                     CDN_HOSTS = (
69                         ('delvenetworks.com', 'cpl.delvenetworks.com'),
70                         ('video.llnw.net', 's2.content.video.llnw.net'),
71                     )
72                     for cdn_host, http_host in CDN_HOSTS:
73                         if cdn_host not in rtmp.group('host').lower():
74                             continue
75                         http_url = 'http://%s/%s' % (http_host, rtmp.group('playpath')[4:])
76                         urls.append(http_url)
77                         if self._is_valid_url(http_url, video_id, http_format_id):
78                             http_fmt = fmt.copy()
79                             http_fmt.update({
80                                 'url': http_url,
81                                 'format_id': http_format_id,
82                             })
83                             formats.append(http_fmt)
84                             break
85
86                     fmt.update({
87                         'url': rtmp.group('url'),
88                         'play_path': rtmp.group('playpath'),
89                         'app': rtmp.group('app'),
90                         'ext': 'flv',
91                         'format_id': format_id,
92                     })
93                 formats.append(fmt)
94
95         for mobile_url in mobile_urls:
96             media_url = mobile_url.get('mobileUrl')
97             format_id = mobile_url.get('targetMediaPlatform')
98             if not media_url or format_id in ('Widevine', 'SmoothStreaming') or media_url in urls:
99                 continue
100             urls.append(media_url)
101             ext = determine_ext(media_url)
102             if ext == 'm3u8':
103                 formats.extend(self._extract_m3u8_formats(
104                     media_url, video_id, 'mp4', 'm3u8_native',
105                     m3u8_id=format_id, fatal=False))
106             elif ext == 'f4m':
107                 formats.extend(self._extract_f4m_formats(
108                     stream_url, video_id, f4m_id=format_id, fatal=False))
109             else:
110                 formats.append({
111                     'url': media_url,
112                     'format_id': format_id,
113                     'preference': -1,
114                     'ext': ext,
115                 })
116
117         self._sort_formats(formats)
118
119         title = properties['title']
120         description = properties.get('description')
121         timestamp = int_or_none(properties.get('publish_date') or properties.get('create_date'))
122         duration = float_or_none(properties.get('duration_in_milliseconds'), 1000)
123         filesize = int_or_none(properties.get('total_storage_in_bytes'))
124         categories = [properties.get('category')]
125         tags = properties.get('tags', [])
126         thumbnails = [{
127             'url': thumbnail['url'],
128             'width': int_or_none(thumbnail.get('width')),
129             'height': int_or_none(thumbnail.get('height')),
130         } for thumbnail in properties.get('thumbnails', []) if thumbnail.get('url')]
131
132         subtitles = {}
133         for caption in properties.get('captions', []):
134             lang = caption.get('language_code')
135             subtitles_url = caption.get('url')
136             if lang and subtitles_url:
137                 subtitles.setdefault(lang, []).append({
138                     'url': subtitles_url,
139                 })
140         closed_captions_url = properties.get('closed_captions_url')
141         if closed_captions_url:
142             subtitles.setdefault('en', []).append({
143                 'url': closed_captions_url,
144                 'ext': 'ttml',
145             })
146
147         return {
148             'id': video_id,
149             'title': title,
150             'description': description,
151             'formats': formats,
152             'timestamp': timestamp,
153             'duration': duration,
154             'filesize': filesize,
155             'categories': categories,
156             'tags': tags,
157             'thumbnails': thumbnails,
158             'subtitles': subtitles,
159         }
160
161
162 class LimelightMediaIE(LimelightBaseIE):
163     IE_NAME = 'limelight'
164     _VALID_URL = r'''(?x)
165                         (?:
166                             limelight:media:|
167                             https?://
168                                 (?:
169                                     link\.videoplatform\.limelight\.com/media/|
170                                     assets\.delvenetworks\.com/player/loader\.swf
171                                 )
172                                 \?.*?\bmediaId=
173                         )
174                         (?P<id>[a-z0-9]{32})
175                     '''
176     _TESTS = [{
177         'url': 'http://link.videoplatform.limelight.com/media/?mediaId=3ffd040b522b4485b6d84effc750cd86',
178         'info_dict': {
179             'id': '3ffd040b522b4485b6d84effc750cd86',
180             'ext': 'mp4',
181             'title': 'HaP and the HB Prince Trailer',
182             'description': 'md5:8005b944181778e313d95c1237ddb640',
183             'thumbnail': r're:^https?://.*\.jpeg$',
184             'duration': 144.23,
185             'timestamp': 1244136834,
186             'upload_date': '20090604',
187         },
188         'params': {
189             # m3u8 download
190             'skip_download': True,
191         },
192     }, {
193         # video with subtitles
194         'url': 'limelight:media:a3e00274d4564ec4a9b29b9466432335',
195         'md5': '2fa3bad9ac321e23860ca23bc2c69e3d',
196         'info_dict': {
197             'id': 'a3e00274d4564ec4a9b29b9466432335',
198             'ext': 'mp4',
199             'title': '3Play Media Overview Video',
200             'thumbnail': r're:^https?://.*\.jpeg$',
201             'duration': 78.101,
202             'timestamp': 1338929955,
203             'upload_date': '20120605',
204             'subtitles': 'mincount:9',
205         },
206     }, {
207         'url': 'https://assets.delvenetworks.com/player/loader.swf?mediaId=8018a574f08d416e95ceaccae4ba0452',
208         'only_matching': True,
209     }]
210     _PLAYLIST_SERVICE_PATH = 'media'
211     _API_PATH = 'media'
212
213     def _real_extract(self, url):
214         url, smuggled_data = unsmuggle_url(url, {})
215         video_id = self._match_id(url)
216
217         pc, mobile, metadata = self._extract(
218             video_id, 'getPlaylistByMediaId',
219             'getMobilePlaylistByMediaId', 'properties',
220             smuggled_data.get('source_url'))
221
222         return self._extract_info(
223             pc['playlistItems'][0].get('streams', []),
224             mobile['mediaList'][0].get('mobileUrls', []) if mobile else [],
225             metadata)
226
227
228 class LimelightChannelIE(LimelightBaseIE):
229     IE_NAME = 'limelight:channel'
230     _VALID_URL = r'''(?x)
231                         (?:
232                             limelight:channel:|
233                             https?://
234                                 (?:
235                                     link\.videoplatform\.limelight\.com/media/|
236                                     assets\.delvenetworks\.com/player/loader\.swf
237                                 )
238                                 \?.*?\bchannelId=
239                         )
240                         (?P<id>[a-z0-9]{32})
241                     '''
242     _TESTS = [{
243         'url': 'http://link.videoplatform.limelight.com/media/?channelId=ab6a524c379342f9b23642917020c082',
244         'info_dict': {
245             'id': 'ab6a524c379342f9b23642917020c082',
246             'title': 'Javascript Sample Code',
247         },
248         'playlist_mincount': 3,
249     }, {
250         'url': 'http://assets.delvenetworks.com/player/loader.swf?channelId=ab6a524c379342f9b23642917020c082',
251         'only_matching': True,
252     }]
253     _PLAYLIST_SERVICE_PATH = 'channel'
254     _API_PATH = 'channels'
255
256     def _real_extract(self, url):
257         url, smuggled_data = unsmuggle_url(url, {})
258         channel_id = self._match_id(url)
259
260         pc, mobile, medias = self._extract(
261             channel_id, 'getPlaylistByChannelId',
262             'getMobilePlaylistWithNItemsByChannelId?begin=0&count=-1',
263             'media', smuggled_data.get('source_url'))
264
265         entries = [
266             self._extract_info(
267                 pc['playlistItems'][i].get('streams', []),
268                 mobile['mediaList'][i].get('mobileUrls', []) if mobile else [],
269                 medias['media_list'][i])
270             for i in range(len(medias['media_list']))]
271
272         return self.playlist_result(entries, channel_id, pc['title'])
273
274
275 class LimelightChannelListIE(LimelightBaseIE):
276     IE_NAME = 'limelight:channel_list'
277     _VALID_URL = r'''(?x)
278                         (?:
279                             limelight:channel_list:|
280                             https?://
281                                 (?:
282                                     link\.videoplatform\.limelight\.com/media/|
283                                     assets\.delvenetworks\.com/player/loader\.swf
284                                 )
285                                 \?.*?\bchannelListId=
286                         )
287                         (?P<id>[a-z0-9]{32})
288                     '''
289     _TESTS = [{
290         'url': 'http://link.videoplatform.limelight.com/media/?channelListId=301b117890c4465c8179ede21fd92e2b',
291         'info_dict': {
292             'id': '301b117890c4465c8179ede21fd92e2b',
293             'title': 'Website - Hero Player',
294         },
295         'playlist_mincount': 2,
296     }, {
297         'url': 'https://assets.delvenetworks.com/player/loader.swf?channelListId=301b117890c4465c8179ede21fd92e2b',
298         'only_matching': True,
299     }]
300     _PLAYLIST_SERVICE_PATH = 'channel_list'
301
302     def _real_extract(self, url):
303         channel_list_id = self._match_id(url)
304
305         channel_list = self._call_playlist_service(channel_list_id, 'getMobileChannelListById')
306
307         entries = [
308             self.url_result('limelight:channel:%s' % channel['id'], 'LimelightChannel')
309             for channel in channel_list['channelList']]
310
311         return self.playlist_result(entries, channel_list_id, channel_list['title'])