]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/turner.py
New upstream version 2018.06.18
[youtubedl] / youtube_dl / extractor / turner.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .adobepass import AdobePassIE
7 from ..compat import compat_str
8 from ..utils import (
9 xpath_text,
10 int_or_none,
11 determine_ext,
12 float_or_none,
13 parse_duration,
14 xpath_attr,
15 update_url_query,
16 ExtractorError,
17 strip_or_none,
18 )
19
20
21 class TurnerBaseIE(AdobePassIE):
22 _AKAMAI_SPE_TOKEN_CACHE = {}
23
24 def _extract_timestamp(self, video_data):
25 return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts'))
26
27 def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None):
28 secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*'
29 token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path)
30 if not token:
31 query = {
32 'path': secure_path,
33 }
34 if custom_tokenizer_query:
35 query.update(custom_tokenizer_query)
36 else:
37 query['videoId'] = content_id
38 if ap_data.get('auth_required'):
39 query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name'])
40 auth = self._download_xml(
41 tokenizer_src, content_id, query=query)
42 error_msg = xpath_text(auth, 'error/msg')
43 if error_msg:
44 raise ExtractorError(error_msg, expected=True)
45 token = xpath_text(auth, 'token')
46 if not token:
47 return video_url
48 self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token
49 return video_url + '?hdnea=' + token
50
51 def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}):
52 video_data = self._download_xml(data_src, video_id)
53 video_id = video_data.attrib['id']
54 title = xpath_text(video_data, 'headline', fatal=True)
55 content_id = xpath_text(video_data, 'contentId') or video_id
56 # rtmp_src = xpath_text(video_data, 'akamai/src')
57 # if rtmp_src:
58 # splited_rtmp_src = rtmp_src.split(',')
59 # if len(splited_rtmp_src) == 2:
60 # rtmp_src = splited_rtmp_src[1]
61 # aifp = xpath_text(video_data, 'akamai/aifp', default='')
62
63 urls = []
64 formats = []
65 rex = re.compile(
66 r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?')
67 # Possible formats locations: files/file, files/groupFiles/files
68 # and maybe others
69 for video_file in video_data.findall('.//file'):
70 video_url = video_file.text.strip()
71 if not video_url:
72 continue
73 ext = determine_ext(video_url)
74 if video_url.startswith('/mp4:protected/'):
75 continue
76 # TODO Correct extraction for these files
77 # protected_path_data = path_data.get('protected')
78 # if not protected_path_data or not rtmp_src:
79 # continue
80 # protected_path = self._search_regex(
81 # r'/mp4:(.+)\.[a-z0-9]', video_url, 'secure path')
82 # auth = self._download_webpage(
83 # protected_path_data['tokenizer_src'], query={
84 # 'path': protected_path,
85 # 'videoId': content_id,
86 # 'aifp': aifp,
87 # })
88 # token = xpath_text(auth, 'token')
89 # if not token:
90 # continue
91 # video_url = rtmp_src + video_url + '?' + token
92 elif video_url.startswith('/secure/'):
93 secure_path_data = path_data.get('secure')
94 if not secure_path_data:
95 continue
96 video_url = self._add_akamai_spe_token(
97 secure_path_data['tokenizer_src'],
98 secure_path_data['media_src'] + video_url,
99 content_id, ap_data)
100 elif not re.match('https?://', video_url):
101 base_path_data = path_data.get(ext, path_data.get('default', {}))
102 media_src = base_path_data.get('media_src')
103 if not media_src:
104 continue
105 video_url = media_src + video_url
106 if video_url in urls:
107 continue
108 urls.append(video_url)
109 format_id = video_file.get('bitrate')
110 if ext == 'smil':
111 formats.extend(self._extract_smil_formats(
112 video_url, video_id, fatal=False))
113 elif ext == 'm3u8':
114 m3u8_formats = self._extract_m3u8_formats(
115 video_url, video_id, 'mp4',
116 m3u8_id=format_id or 'hls', fatal=False)
117 if '/secure/' in video_url and '?hdnea=' in video_url:
118 for f in m3u8_formats:
119 f['_seekable'] = False
120 formats.extend(m3u8_formats)
121 elif ext == 'f4m':
122 formats.extend(self._extract_f4m_formats(
123 update_url_query(video_url, {'hdcore': '3.7.0'}),
124 video_id, f4m_id=format_id or 'hds', fatal=False))
125 else:
126 f = {
127 'format_id': format_id,
128 'url': video_url,
129 'ext': ext,
130 }
131 mobj = rex.search(format_id + video_url)
132 if mobj:
133 f.update({
134 'width': int(mobj.group('width')),
135 'height': int(mobj.group('height')),
136 'tbr': int_or_none(mobj.group('bitrate')),
137 })
138 elif isinstance(format_id, compat_str):
139 if format_id.isdigit():
140 f['tbr'] = int(format_id)
141 else:
142 mobj = re.match(r'ios_(audio|[0-9]+)$', format_id)
143 if mobj:
144 if mobj.group(1) == 'audio':
145 f.update({
146 'vcodec': 'none',
147 'ext': 'm4a',
148 })
149 else:
150 f['tbr'] = int(mobj.group(1))
151 formats.append(f)
152 self._sort_formats(formats)
153
154 subtitles = {}
155 for source in video_data.findall('closedCaptions/source'):
156 for track in source.findall('track'):
157 track_url = track.get('url')
158 if not isinstance(track_url, compat_str) or track_url.endswith('/big'):
159 continue
160 lang = track.get('lang') or track.get('label') or 'en'
161 subtitles.setdefault(lang, []).append({
162 'url': track_url,
163 'ext': {
164 'scc': 'scc',
165 'webvtt': 'vtt',
166 'smptett': 'tt',
167 }.get(source.get('format'))
168 })
169
170 thumbnails = [{
171 'id': image.get('cut'),
172 'url': image.text,
173 'width': int_or_none(image.get('width')),
174 'height': int_or_none(image.get('height')),
175 } for image in video_data.findall('images/image')]
176
177 is_live = xpath_text(video_data, 'isLive') == 'true'
178
179 return {
180 'id': video_id,
181 'title': self._live_title(title) if is_live else title,
182 'formats': formats,
183 'subtitles': subtitles,
184 'thumbnails': thumbnails,
185 'thumbnail': xpath_text(video_data, 'poster'),
186 'description': strip_or_none(xpath_text(video_data, 'description')),
187 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),
188 'timestamp': self._extract_timestamp(video_data),
189 'upload_date': xpath_attr(video_data, 'metas', 'version'),
190 'series': xpath_text(video_data, 'showTitle'),
191 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),
192 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),
193 'is_live': is_live,
194 }
195
196 def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None):
197 streams_data = self._download_json(
198 'http://medium.ngtv.io/media/%s/tv' % media_id,
199 media_id)['media']['tv']
200 duration = None
201 chapters = []
202 formats = []
203 for supported_type in ('unprotected', 'bulkaes'):
204 stream_data = streams_data.get(supported_type, {})
205 m3u8_url = stream_data.get('secureUrl') or stream_data.get('url')
206 if not m3u8_url:
207 continue
208 if stream_data.get('playlistProtection') == 'spe':
209 m3u8_url = self._add_akamai_spe_token(
210 'http://token.ngtv.io/token/token_spe',
211 m3u8_url, media_id, ap_data or {}, tokenizer_query)
212 formats.extend(self._extract_m3u8_formats(
213 m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False))
214
215 duration = float_or_none(stream_data.get('totalRuntime'))
216
217 if not chapters:
218 for chapter in stream_data.get('contentSegments', []):
219 start_time = float_or_none(chapter.get('start'))
220 chapter_duration = float_or_none(chapter.get('duration'))
221 if start_time is None or chapter_duration is None:
222 continue
223 chapters.append({
224 'start_time': start_time,
225 'end_time': start_time + chapter_duration,
226 })
227 self._sort_formats(formats)
228
229 return {
230 'formats': formats,
231 'chapters': chapters,
232 'duration': duration,
233 }