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