]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/limelight.py
New upstream version 2020.03.24
[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 try_get,
14 unsmuggle_url,
15 ExtractorError,
16 )
17
18
19 class LimelightBaseIE(InfoExtractor):
20 _PLAYLIST_SERVICE_URL = 'http://production-ps.lvp.llnw.net/r/PlaylistService/%s/%s/%s'
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,
73 fatal=fatal, headers=headers)
74 except ExtractorError as e:
75 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
76 error = self._parse_json(e.cause.read().decode(), item_id)['detail']['contentAccessPermission']
77 if error == 'CountryDisabled':
78 self.raise_geo_restricted()
79 raise ExtractorError(error, expected=True)
80 raise
81
82 def _extract(self, item_id, pc_method, mobile_method, referer=None):
83 pc = self._call_playlist_service(item_id, pc_method, referer=referer)
84 mobile = self._call_playlist_service(
85 item_id, mobile_method, fatal=False, referer=referer)
86 return pc, mobile
87
88 def _extract_info(self, pc, mobile, i, referer):
89 get_item = lambda x, y: try_get(x, lambda x: x[y][i], dict) or {}
90 pc_item = get_item(pc, 'playlistItems')
91 mobile_item = get_item(mobile, 'mediaList')
92 video_id = pc_item.get('mediaId') or mobile_item['mediaId']
93 title = pc_item.get('title') or mobile_item['title']
94
95 formats = []
96 urls = []
97 for stream in pc_item.get('streams', []):
98 stream_url = stream.get('url')
99 if not stream_url or stream.get('drmProtected') or stream_url in urls:
100 continue
101 urls.append(stream_url)
102 ext = determine_ext(stream_url)
103 if ext == 'f4m':
104 formats.extend(self._extract_f4m_formats(
105 stream_url, video_id, f4m_id='hds', fatal=False))
106 else:
107 fmt = {
108 'url': stream_url,
109 'abr': float_or_none(stream.get('audioBitRate')),
110 'fps': float_or_none(stream.get('videoFrameRate')),
111 'ext': ext,
112 }
113 width = int_or_none(stream.get('videoWidthInPixels'))
114 height = int_or_none(stream.get('videoHeightInPixels'))
115 vbr = float_or_none(stream.get('videoBitRate'))
116 if width or height or vbr:
117 fmt.update({
118 'width': width,
119 'height': height,
120 'vbr': vbr,
121 })
122 else:
123 fmt['vcodec'] = 'none'
124 rtmp = re.search(r'^(?P<url>rtmpe?://(?P<host>[^/]+)/(?P<app>.+))/(?P<playpath>mp[34]:.+)$', stream_url)
125 if rtmp:
126 format_id = 'rtmp'
127 if stream.get('videoBitRate'):
128 format_id += '-%d' % int_or_none(stream['videoBitRate'])
129 http_format_id = format_id.replace('rtmp', 'http')
130
131 CDN_HOSTS = (
132 ('delvenetworks.com', 'cpl.delvenetworks.com'),
133 ('video.llnw.net', 's2.content.video.llnw.net'),
134 )
135 for cdn_host, http_host in CDN_HOSTS:
136 if cdn_host not in rtmp.group('host').lower():
137 continue
138 http_url = 'http://%s/%s' % (http_host, rtmp.group('playpath')[4:])
139 urls.append(http_url)
140 if self._is_valid_url(http_url, video_id, http_format_id):
141 http_fmt = fmt.copy()
142 http_fmt.update({
143 'url': http_url,
144 'format_id': http_format_id,
145 })
146 formats.append(http_fmt)
147 break
148
149 fmt.update({
150 'url': rtmp.group('url'),
151 'play_path': rtmp.group('playpath'),
152 'app': rtmp.group('app'),
153 'ext': 'flv',
154 'format_id': format_id,
155 })
156 formats.append(fmt)
157
158 for mobile_url in mobile_item.get('mobileUrls', []):
159 media_url = mobile_url.get('mobileUrl')
160 format_id = mobile_url.get('targetMediaPlatform')
161 if not media_url or format_id in ('Widevine', 'SmoothStreaming') or media_url in urls:
162 continue
163 urls.append(media_url)
164 ext = determine_ext(media_url)
165 if ext == 'm3u8':
166 formats.extend(self._extract_m3u8_formats(
167 media_url, video_id, 'mp4', 'm3u8_native',
168 m3u8_id=format_id, fatal=False))
169 elif ext == 'f4m':
170 formats.extend(self._extract_f4m_formats(
171 stream_url, video_id, f4m_id=format_id, fatal=False))
172 else:
173 formats.append({
174 'url': media_url,
175 'format_id': format_id,
176 'preference': -1,
177 'ext': ext,
178 })
179
180 self._sort_formats(formats)
181
182 subtitles = {}
183 for flag in mobile_item.get('flags'):
184 if flag == 'ClosedCaptions':
185 closed_captions = self._call_playlist_service(
186 video_id, 'getClosedCaptionsDetailsByMediaId',
187 False, referer) or []
188 for cc in closed_captions:
189 cc_url = cc.get('webvttFileUrl')
190 if not cc_url:
191 continue
192 lang = cc.get('languageCode') or self._search_regex(r'/[a-z]{2}\.vtt', cc_url, 'lang', default='en')
193 subtitles.setdefault(lang, []).append({
194 'url': cc_url,
195 })
196 break
197
198 get_meta = lambda x: pc_item.get(x) or mobile_item.get(x)
199
200 return {
201 'id': video_id,
202 'title': title,
203 'description': get_meta('description'),
204 'formats': formats,
205 'duration': float_or_none(get_meta('durationInMilliseconds'), 1000),
206 'thumbnail': get_meta('previewImageUrl') or get_meta('thumbnailImageUrl'),
207 'subtitles': subtitles,
208 }
209
210
211 class LimelightMediaIE(LimelightBaseIE):
212 IE_NAME = 'limelight'
213 _VALID_URL = r'''(?x)
214 (?:
215 limelight:media:|
216 https?://
217 (?:
218 link\.videoplatform\.limelight\.com/media/|
219 assets\.delvenetworks\.com/player/loader\.swf
220 )
221 \?.*?\bmediaId=
222 )
223 (?P<id>[a-z0-9]{32})
224 '''
225 _TESTS = [{
226 'url': 'http://link.videoplatform.limelight.com/media/?mediaId=3ffd040b522b4485b6d84effc750cd86',
227 'info_dict': {
228 'id': '3ffd040b522b4485b6d84effc750cd86',
229 'ext': 'mp4',
230 'title': 'HaP and the HB Prince Trailer',
231 'description': 'md5:8005b944181778e313d95c1237ddb640',
232 'thumbnail': r're:^https?://.*\.jpeg$',
233 'duration': 144.23,
234 },
235 'params': {
236 # m3u8 download
237 'skip_download': True,
238 },
239 }, {
240 # video with subtitles
241 'url': 'limelight:media:a3e00274d4564ec4a9b29b9466432335',
242 'md5': '2fa3bad9ac321e23860ca23bc2c69e3d',
243 'info_dict': {
244 'id': 'a3e00274d4564ec4a9b29b9466432335',
245 'ext': 'mp4',
246 'title': '3Play Media Overview Video',
247 'thumbnail': r're:^https?://.*\.jpeg$',
248 'duration': 78.101,
249 # TODO: extract all languages that were accessible via API
250 # 'subtitles': 'mincount:9',
251 'subtitles': 'mincount:1',
252 },
253 }, {
254 'url': 'https://assets.delvenetworks.com/player/loader.swf?mediaId=8018a574f08d416e95ceaccae4ba0452',
255 'only_matching': True,
256 }]
257 _PLAYLIST_SERVICE_PATH = 'media'
258
259 def _real_extract(self, url):
260 url, smuggled_data = unsmuggle_url(url, {})
261 video_id = self._match_id(url)
262 source_url = smuggled_data.get('source_url')
263 self._initialize_geo_bypass({
264 'countries': smuggled_data.get('geo_countries'),
265 })
266
267 pc, mobile = self._extract(
268 video_id, 'getPlaylistByMediaId',
269 'getMobilePlaylistByMediaId', source_url)
270
271 return self._extract_info(pc, mobile, 0, source_url)
272
273
274 class LimelightChannelIE(LimelightBaseIE):
275 IE_NAME = 'limelight:channel'
276 _VALID_URL = r'''(?x)
277 (?:
278 limelight:channel:|
279 https?://
280 (?:
281 link\.videoplatform\.limelight\.com/media/|
282 assets\.delvenetworks\.com/player/loader\.swf
283 )
284 \?.*?\bchannelId=
285 )
286 (?P<id>[a-z0-9]{32})
287 '''
288 _TESTS = [{
289 'url': 'http://link.videoplatform.limelight.com/media/?channelId=ab6a524c379342f9b23642917020c082',
290 'info_dict': {
291 'id': 'ab6a524c379342f9b23642917020c082',
292 'title': 'Javascript Sample Code',
293 'description': 'Javascript Sample Code - http://www.delvenetworks.com/sample-code/playerCode-demo.html',
294 },
295 'playlist_mincount': 3,
296 }, {
297 'url': 'http://assets.delvenetworks.com/player/loader.swf?channelId=ab6a524c379342f9b23642917020c082',
298 'only_matching': True,
299 }]
300 _PLAYLIST_SERVICE_PATH = 'channel'
301
302 def _real_extract(self, url):
303 url, smuggled_data = unsmuggle_url(url, {})
304 channel_id = self._match_id(url)
305 source_url = smuggled_data.get('source_url')
306
307 pc, mobile = self._extract(
308 channel_id, 'getPlaylistByChannelId',
309 'getMobilePlaylistWithNItemsByChannelId?begin=0&count=-1',
310 source_url)
311
312 entries = [
313 self._extract_info(pc, mobile, i, source_url)
314 for i in range(len(pc['playlistItems']))]
315
316 return self.playlist_result(
317 entries, channel_id, pc.get('title'), mobile.get('description'))
318
319
320 class LimelightChannelListIE(LimelightBaseIE):
321 IE_NAME = 'limelight:channel_list'
322 _VALID_URL = r'''(?x)
323 (?:
324 limelight:channel_list:|
325 https?://
326 (?:
327 link\.videoplatform\.limelight\.com/media/|
328 assets\.delvenetworks\.com/player/loader\.swf
329 )
330 \?.*?\bchannelListId=
331 )
332 (?P<id>[a-z0-9]{32})
333 '''
334 _TESTS = [{
335 'url': 'http://link.videoplatform.limelight.com/media/?channelListId=301b117890c4465c8179ede21fd92e2b',
336 'info_dict': {
337 'id': '301b117890c4465c8179ede21fd92e2b',
338 'title': 'Website - Hero Player',
339 },
340 'playlist_mincount': 2,
341 }, {
342 'url': 'https://assets.delvenetworks.com/player/loader.swf?channelListId=301b117890c4465c8179ede21fd92e2b',
343 'only_matching': True,
344 }]
345 _PLAYLIST_SERVICE_PATH = 'channel_list'
346
347 def _real_extract(self, url):
348 channel_list_id = self._match_id(url)
349
350 channel_list = self._call_playlist_service(
351 channel_list_id, 'getMobileChannelListById')
352
353 entries = [
354 self.url_result('limelight:channel:%s' % channel['id'], 'LimelightChannel')
355 for channel in channel_list['channelList']]
356
357 return self.playlist_result(
358 entries, channel_list_id, channel_list['title'])