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