]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/limelight.py
Prepare to release.
[youtubedl] / 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 ..compat import compat_HTTPError
8 from ..utils import (
9 determine_ext,
10 float_or_none,
11 int_or_none,
12 smuggle_url,
13 unsmuggle_url,
14 ExtractorError,
15 )
16
17
18 class LimelightBaseIE(InfoExtractor):
19 _PLAYLIST_SERVICE_URL = 'http://production-ps.lvp.llnw.net/r/PlaylistService/%s/%s/%s'
20 _API_URL = 'http://api.video.limelight.com/rest/organizations/%s/%s/%s/%s.json'
21
22 @classmethod
23 def _extract_urls(cls, webpage, source_url):
24 lm = {
25 'Media': 'media',
26 'Channel': 'channel',
27 'ChannelList': 'channel_list',
28 }
29 entries = []
30 for kind, video_id in re.findall(
31 r'LimelightPlayer\.doLoad(Media|Channel|ChannelList)\(["\'](?P<id>[a-z0-9]{32})',
32 webpage):
33 entries.append(cls.url_result(
34 smuggle_url(
35 'limelight:%s:%s' % (lm[kind], video_id),
36 {'source_url': source_url}),
37 'Limelight%s' % kind, video_id))
38 for mobj in re.finditer(
39 # As per [1] class attribute should be exactly equal to
40 # LimelightEmbeddedPlayerFlash but numerous examples seen
41 # that don't exactly match it (e.g. [2]).
42 # 1. http://support.3playmedia.com/hc/en-us/articles/227732408-Limelight-Embedding-the-Captions-Plugin-with-the-Limelight-Player-on-Your-Webpage
43 # 2. http://www.sedona.com/FacilitatorTraining2017
44 r'''(?sx)
45 <object[^>]+class=(["\'])(?:(?!\1).)*\bLimelightEmbeddedPlayerFlash\b(?:(?!\1).)*\1[^>]*>.*?
46 <param[^>]+
47 name=(["\'])flashVars\2[^>]+
48 value=(["\'])(?:(?!\3).)*(?P<kind>media|channel(?:List)?)Id=(?P<id>[a-z0-9]{32})
49 ''', webpage):
50 kind, video_id = mobj.group('kind'), mobj.group('id')
51 entries.append(cls.url_result(
52 smuggle_url(
53 'limelight:%s:%s' % (kind, video_id),
54 {'source_url': source_url}),
55 'Limelight%s' % kind.capitalize(), video_id))
56 return entries
57
58 def _call_playlist_service(self, item_id, method, fatal=True, referer=None):
59 headers = {}
60 if referer:
61 headers['Referer'] = referer
62 try:
63 return self._download_json(
64 self._PLAYLIST_SERVICE_URL % (self._PLAYLIST_SERVICE_PATH, item_id, method),
65 item_id, 'Downloading PlaylistService %s JSON' % method, fatal=fatal, headers=headers)
66 except ExtractorError as e:
67 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
68 error = self._parse_json(e.cause.read().decode(), item_id)['detail']['contentAccessPermission']
69 if error == 'CountryDisabled':
70 self.raise_geo_restricted()
71 raise ExtractorError(error, expected=True)
72 raise
73
74 def _call_api(self, organization_id, item_id, method):
75 return self._download_json(
76 self._API_URL % (organization_id, self._API_PATH, item_id, method),
77 item_id, 'Downloading API %s JSON' % method)
78
79 def _extract(self, item_id, pc_method, mobile_method, meta_method, referer=None):
80 pc = self._call_playlist_service(item_id, pc_method, referer=referer)
81 metadata = self._call_api(pc['orgId'], item_id, meta_method)
82 mobile = self._call_playlist_service(item_id, mobile_method, fatal=False, referer=referer)
83 return pc, mobile, metadata
84
85 def _extract_info(self, streams, mobile_urls, properties):
86 video_id = properties['media_id']
87 formats = []
88 urls = []
89 for stream in streams:
90 stream_url = stream.get('url')
91 if not stream_url or stream.get('drmProtected') or stream_url in urls:
92 continue
93 urls.append(stream_url)
94 ext = determine_ext(stream_url)
95 if ext == 'f4m':
96 formats.extend(self._extract_f4m_formats(
97 stream_url, video_id, f4m_id='hds', fatal=False))
98 else:
99 fmt = {
100 'url': stream_url,
101 'abr': float_or_none(stream.get('audioBitRate')),
102 'fps': float_or_none(stream.get('videoFrameRate')),
103 'ext': ext,
104 }
105 width = int_or_none(stream.get('videoWidthInPixels'))
106 height = int_or_none(stream.get('videoHeightInPixels'))
107 vbr = float_or_none(stream.get('videoBitRate'))
108 if width or height or vbr:
109 fmt.update({
110 'width': width,
111 'height': height,
112 'vbr': vbr,
113 })
114 else:
115 fmt['vcodec'] = 'none'
116 rtmp = re.search(r'^(?P<url>rtmpe?://(?P<host>[^/]+)/(?P<app>.+))/(?P<playpath>mp[34]:.+)$', stream_url)
117 if rtmp:
118 format_id = 'rtmp'
119 if stream.get('videoBitRate'):
120 format_id += '-%d' % int_or_none(stream['videoBitRate'])
121 http_format_id = format_id.replace('rtmp', 'http')
122
123 CDN_HOSTS = (
124 ('delvenetworks.com', 'cpl.delvenetworks.com'),
125 ('video.llnw.net', 's2.content.video.llnw.net'),
126 )
127 for cdn_host, http_host in CDN_HOSTS:
128 if cdn_host not in rtmp.group('host').lower():
129 continue
130 http_url = 'http://%s/%s' % (http_host, rtmp.group('playpath')[4:])
131 urls.append(http_url)
132 if self._is_valid_url(http_url, video_id, http_format_id):
133 http_fmt = fmt.copy()
134 http_fmt.update({
135 'url': http_url,
136 'format_id': http_format_id,
137 })
138 formats.append(http_fmt)
139 break
140
141 fmt.update({
142 'url': rtmp.group('url'),
143 'play_path': rtmp.group('playpath'),
144 'app': rtmp.group('app'),
145 'ext': 'flv',
146 'format_id': format_id,
147 })
148 formats.append(fmt)
149
150 for mobile_url in mobile_urls:
151 media_url = mobile_url.get('mobileUrl')
152 format_id = mobile_url.get('targetMediaPlatform')
153 if not media_url or format_id in ('Widevine', 'SmoothStreaming') or media_url in urls:
154 continue
155 urls.append(media_url)
156 ext = determine_ext(media_url)
157 if ext == 'm3u8':
158 formats.extend(self._extract_m3u8_formats(
159 media_url, video_id, 'mp4', 'm3u8_native',
160 m3u8_id=format_id, fatal=False))
161 elif ext == 'f4m':
162 formats.extend(self._extract_f4m_formats(
163 stream_url, video_id, f4m_id=format_id, fatal=False))
164 else:
165 formats.append({
166 'url': media_url,
167 'format_id': format_id,
168 'preference': -1,
169 'ext': ext,
170 })
171
172 self._sort_formats(formats)
173
174 title = properties['title']
175 description = properties.get('description')
176 timestamp = int_or_none(properties.get('publish_date') or properties.get('create_date'))
177 duration = float_or_none(properties.get('duration_in_milliseconds'), 1000)
178 filesize = int_or_none(properties.get('total_storage_in_bytes'))
179 categories = [properties.get('category')]
180 tags = properties.get('tags', [])
181 thumbnails = [{
182 'url': thumbnail['url'],
183 'width': int_or_none(thumbnail.get('width')),
184 'height': int_or_none(thumbnail.get('height')),
185 } for thumbnail in properties.get('thumbnails', []) if thumbnail.get('url')]
186
187 subtitles = {}
188 for caption in properties.get('captions', []):
189 lang = caption.get('language_code')
190 subtitles_url = caption.get('url')
191 if lang and subtitles_url:
192 subtitles.setdefault(lang, []).append({
193 'url': subtitles_url,
194 })
195 closed_captions_url = properties.get('closed_captions_url')
196 if closed_captions_url:
197 subtitles.setdefault('en', []).append({
198 'url': closed_captions_url,
199 'ext': 'ttml',
200 })
201
202 return {
203 'id': video_id,
204 'title': title,
205 'description': description,
206 'formats': formats,
207 'timestamp': timestamp,
208 'duration': duration,
209 'filesize': filesize,
210 'categories': categories,
211 'tags': tags,
212 'thumbnails': thumbnails,
213 'subtitles': subtitles,
214 }
215
216
217 class LimelightMediaIE(LimelightBaseIE):
218 IE_NAME = 'limelight'
219 _VALID_URL = r'''(?x)
220 (?:
221 limelight:media:|
222 https?://
223 (?:
224 link\.videoplatform\.limelight\.com/media/|
225 assets\.delvenetworks\.com/player/loader\.swf
226 )
227 \?.*?\bmediaId=
228 )
229 (?P<id>[a-z0-9]{32})
230 '''
231 _TESTS = [{
232 'url': 'http://link.videoplatform.limelight.com/media/?mediaId=3ffd040b522b4485b6d84effc750cd86',
233 'info_dict': {
234 'id': '3ffd040b522b4485b6d84effc750cd86',
235 'ext': 'mp4',
236 'title': 'HaP and the HB Prince Trailer',
237 'description': 'md5:8005b944181778e313d95c1237ddb640',
238 'thumbnail': r're:^https?://.*\.jpeg$',
239 'duration': 144.23,
240 'timestamp': 1244136834,
241 'upload_date': '20090604',
242 },
243 'params': {
244 # m3u8 download
245 'skip_download': True,
246 },
247 }, {
248 # video with subtitles
249 'url': 'limelight:media:a3e00274d4564ec4a9b29b9466432335',
250 'md5': '2fa3bad9ac321e23860ca23bc2c69e3d',
251 'info_dict': {
252 'id': 'a3e00274d4564ec4a9b29b9466432335',
253 'ext': 'mp4',
254 'title': '3Play Media Overview Video',
255 'thumbnail': r're:^https?://.*\.jpeg$',
256 'duration': 78.101,
257 'timestamp': 1338929955,
258 'upload_date': '20120605',
259 'subtitles': 'mincount:9',
260 },
261 }, {
262 'url': 'https://assets.delvenetworks.com/player/loader.swf?mediaId=8018a574f08d416e95ceaccae4ba0452',
263 'only_matching': True,
264 }]
265 _PLAYLIST_SERVICE_PATH = 'media'
266 _API_PATH = 'media'
267
268 def _real_extract(self, url):
269 url, smuggled_data = unsmuggle_url(url, {})
270 video_id = self._match_id(url)
271 self._initialize_geo_bypass(smuggled_data.get('geo_countries'))
272
273 pc, mobile, metadata = self._extract(
274 video_id, 'getPlaylistByMediaId',
275 'getMobilePlaylistByMediaId', 'properties',
276 smuggled_data.get('source_url'))
277
278 return self._extract_info(
279 pc['playlistItems'][0].get('streams', []),
280 mobile['mediaList'][0].get('mobileUrls', []) if mobile else [],
281 metadata)
282
283
284 class LimelightChannelIE(LimelightBaseIE):
285 IE_NAME = 'limelight:channel'
286 _VALID_URL = r'''(?x)
287 (?:
288 limelight:channel:|
289 https?://
290 (?:
291 link\.videoplatform\.limelight\.com/media/|
292 assets\.delvenetworks\.com/player/loader\.swf
293 )
294 \?.*?\bchannelId=
295 )
296 (?P<id>[a-z0-9]{32})
297 '''
298 _TESTS = [{
299 'url': 'http://link.videoplatform.limelight.com/media/?channelId=ab6a524c379342f9b23642917020c082',
300 'info_dict': {
301 'id': 'ab6a524c379342f9b23642917020c082',
302 'title': 'Javascript Sample Code',
303 },
304 'playlist_mincount': 3,
305 }, {
306 'url': 'http://assets.delvenetworks.com/player/loader.swf?channelId=ab6a524c379342f9b23642917020c082',
307 'only_matching': True,
308 }]
309 _PLAYLIST_SERVICE_PATH = 'channel'
310 _API_PATH = 'channels'
311
312 def _real_extract(self, url):
313 url, smuggled_data = unsmuggle_url(url, {})
314 channel_id = self._match_id(url)
315
316 pc, mobile, medias = self._extract(
317 channel_id, 'getPlaylistByChannelId',
318 'getMobilePlaylistWithNItemsByChannelId?begin=0&count=-1',
319 'media', smuggled_data.get('source_url'))
320
321 entries = [
322 self._extract_info(
323 pc['playlistItems'][i].get('streams', []),
324 mobile['mediaList'][i].get('mobileUrls', []) if mobile else [],
325 medias['media_list'][i])
326 for i in range(len(medias['media_list']))]
327
328 return self.playlist_result(entries, channel_id, pc['title'])
329
330
331 class LimelightChannelListIE(LimelightBaseIE):
332 IE_NAME = 'limelight:channel_list'
333 _VALID_URL = r'''(?x)
334 (?:
335 limelight:channel_list:|
336 https?://
337 (?:
338 link\.videoplatform\.limelight\.com/media/|
339 assets\.delvenetworks\.com/player/loader\.swf
340 )
341 \?.*?\bchannelListId=
342 )
343 (?P<id>[a-z0-9]{32})
344 '''
345 _TESTS = [{
346 'url': 'http://link.videoplatform.limelight.com/media/?channelListId=301b117890c4465c8179ede21fd92e2b',
347 'info_dict': {
348 'id': '301b117890c4465c8179ede21fd92e2b',
349 'title': 'Website - Hero Player',
350 },
351 'playlist_mincount': 2,
352 }, {
353 'url': 'https://assets.delvenetworks.com/player/loader.swf?channelListId=301b117890c4465c8179ede21fd92e2b',
354 'only_matching': True,
355 }]
356 _PLAYLIST_SERVICE_PATH = 'channel_list'
357
358 def _real_extract(self, url):
359 channel_list_id = self._match_id(url)
360
361 channel_list = self._call_playlist_service(channel_list_id, 'getMobileChannelListById')
362
363 entries = [
364 self.url_result('limelight:channel:%s' % channel['id'], 'LimelightChannel')
365 for channel in channel_list['channelList']]
366
367 return self.playlist_result(entries, channel_list_id, channel_list['title'])