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