]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/turner.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[yt-dlp.git] / yt_dlp / extractor / turner.py
1 import re
2
3 from .adobepass import AdobePassIE
4 from ..compat import compat_str
5 from ..utils import (
6 ExtractorError,
7 determine_ext,
8 fix_xml_ampersands,
9 float_or_none,
10 int_or_none,
11 parse_duration,
12 strip_or_none,
13 update_url_query,
14 url_or_none,
15 xpath_attr,
16 xpath_text,
17 )
18
19
20 class TurnerBaseIE(AdobePassIE):
21 _AKAMAI_SPE_TOKEN_CACHE = {}
22
23 def _extract_timestamp(self, video_data):
24 return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts'))
25
26 def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None):
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,
32 }
33 if custom_tokenizer_query:
34 query.update(custom_tokenizer_query)
35 else:
36 query['videoId'] = content_id
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
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 {}
57 video_id = video_data.attrib['id']
58 title = xpath_text(video_data, 'headline', fatal=True)
59 content_id = xpath_text(video_data, 'contentId') or video_id
60 # rtmp_src = xpath_text(video_data, 'akamai/src')
61 # if rtmp_src:
62 # split_rtmp_src = rtmp_src.split(',')
63 # if len(split_rtmp_src) == 2:
64 # rtmp_src = split_rtmp_src[1]
65 # aifp = xpath_text(video_data, 'akamai/aifp', default='')
66
67 urls = []
68 formats = []
69 thumbnails = []
70 subtitles = {}
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'):
76 video_url = url_or_none(video_file.text.strip())
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,
91 # 'videoId': content_id,
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
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)
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)
115 format_id = video_file.get('bitrate')
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':
127 formats.extend(self._extract_smil_formats(
128 video_url, video_id, fatal=False))
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 }))
138 elif ext == 'm3u8':
139 m3u8_formats = self._extract_m3u8_formats(
140 video_url, video_id, 'mp4',
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:
144 f['downloader_options'] = {'ffmpeg_args': ['-seekable', '0']}
145 formats.extend(m3u8_formats)
146 elif ext == 'f4m':
147 formats.extend(self._extract_f4m_formats(
148 update_url_query(video_url, {'hdcore': '3.7.0'}),
149 video_id, f4m_id=format_id or 'hds', fatal=False))
150 else:
151 f = {
152 'format_id': format_id,
153 'url': video_url,
154 'ext': ext,
155 }
156 mobj = rex.search(video_url)
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 })
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))
176 formats.append(f)
177
178 for source in video_data.findall('closedCaptions/source'):
179 for track in source.findall('track'):
180 track_url = url_or_none(track.get('url'))
181 if not track_url or track_url.endswith('/big'):
182 continue
183 lang = track.get('lang') or track.get('label') or 'en'
184 subtitles.setdefault(lang, []).append({
185 'url': track_url,
186 'ext': {
187 'scc': 'scc',
188 'webvtt': 'vtt',
189 'smptett': 'tt',
190 }.get(source.get('format'))
191 })
192
193 thumbnails.extend({
194 'id': image.get('cut') or image.get('name'),
195 'url': image.text,
196 'width': int_or_none(image.get('width')),
197 'height': int_or_none(image.get('height')),
198 } for image in video_data.findall('images/image'))
199
200 is_live = xpath_text(video_data, 'isLive') == 'true'
201
202 return {
203 'id': video_id,
204 'title': title,
205 'formats': formats,
206 'subtitles': subtitles,
207 'thumbnails': thumbnails,
208 'thumbnail': xpath_text(video_data, 'poster'),
209 'description': strip_or_none(xpath_text(video_data, 'description')),
210 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),
211 'timestamp': self._extract_timestamp(video_data),
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')),
216 'is_live': is_live,
217 }
218
219 def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None):
220 is_live = ap_data.get('is_live')
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(
237 m3u8_url, media_id, 'mp4', m3u8_id='hls', live=is_live, fatal=False))
238
239 duration = float_or_none(stream_data.get('totalRuntime'))
240
241 if not chapters and not is_live:
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 })
251
252 return {
253 'formats': formats,
254 'chapters': chapters,
255 'duration': duration,
256 }