]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/turner.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[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 (
e897bd82 6 ExtractorError,
29825140 7 determine_ext,
e897bd82 8 fix_xml_ampersands,
e0d42dd4 9 float_or_none,
e897bd82 10 int_or_none,
29825140 11 parse_duration,
04c09f19 12 strip_or_none,
e897bd82 13 update_url_query,
3052a30d 14 url_or_none,
e897bd82
SS
15 xpath_attr,
16 xpath_text,
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 176 formats.append(f)
29825140 177
29825140
RA
178 for source in video_data.findall('closedCaptions/source'):
179 for track in source.findall('track'):
3052a30d
S
180 track_url = url_or_none(track.get('url'))
181 if not track_url or track_url.endswith('/big'):
29825140 182 continue
547993dc
S
183 lang = track.get('lang') or track.get('label') or 'en'
184 subtitles.setdefault(lang, []).append({
185 'url': track_url,
29825140
RA
186 'ext': {
187 'scc': 'scc',
188 'webvtt': 'vtt',
189 'smptett': 'tt',
190 }.get(source.get('format'))
191 })
192
29f7c58a 193 thumbnails.extend({
194 'id': image.get('cut') or image.get('name'),
29825140
RA
195 'url': image.text,
196 'width': int_or_none(image.get('width')),
197 'height': int_or_none(image.get('height')),
29f7c58a 198 } for image in video_data.findall('images/image'))
29825140 199
04c09f19
RA
200 is_live = xpath_text(video_data, 'isLive') == 'true'
201
29825140
RA
202 return {
203 'id': video_id,
39ca3b5c 204 'title': title,
29825140
RA
205 'formats': formats,
206 'subtitles': subtitles,
207 'thumbnails': thumbnails,
04c09f19
RA
208 'thumbnail': xpath_text(video_data, 'poster'),
209 'description': strip_or_none(xpath_text(video_data, 'description')),
29825140 210 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),
da30a20a 211 'timestamp': self._extract_timestamp(video_data),
29825140
RA
212 'upload_date': xpath_attr(video_data, 'metas', 'version'),
213 'series': xpath_text(video_data, 'showTitle'),
214 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),
215 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),
04c09f19 216 'is_live': is_live,
29825140 217 }
e0d42dd4
RA
218
219 def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None):
1e79316e 220 is_live = ap_data.get('is_live')
e0d42dd4
RA
221 streams_data = self._download_json(
222 'http://medium.ngtv.io/media/%s/tv' % media_id,
223 media_id)['media']['tv']
224 duration = None
225 chapters = []
226 formats = []
227 for supported_type in ('unprotected', 'bulkaes'):
228 stream_data = streams_data.get(supported_type, {})
229 m3u8_url = stream_data.get('secureUrl') or stream_data.get('url')
230 if not m3u8_url:
231 continue
232 if stream_data.get('playlistProtection') == 'spe':
233 m3u8_url = self._add_akamai_spe_token(
234 'http://token.ngtv.io/token/token_spe',
235 m3u8_url, media_id, ap_data or {}, tokenizer_query)
236 formats.extend(self._extract_m3u8_formats(
1e79316e 237 m3u8_url, media_id, 'mp4', m3u8_id='hls', live=is_live, fatal=False))
e0d42dd4
RA
238
239 duration = float_or_none(stream_data.get('totalRuntime'))
240
1e79316e 241 if not chapters and not is_live:
e0d42dd4
RA
242 for chapter in stream_data.get('contentSegments', []):
243 start_time = float_or_none(chapter.get('start'))
244 chapter_duration = float_or_none(chapter.get('duration'))
245 if start_time is None or chapter_duration is None:
246 continue
247 chapters.append({
248 'start_time': start_time,
249 'end_time': start_time + chapter_duration,
250 })
e0d42dd4
RA
251
252 return {
253 'formats': formats,
254 'chapters': chapters,
255 'duration': duration,
256 }