]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/itv.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[yt-dlp.git] / yt_dlp / extractor / itv.py
CommitLineData
a71b8d3b
RA
1import json
2
ea1f5e5d 3from .brightcove import BrightcoveNewIE
e897bd82 4from .common import InfoExtractor
ea706726 5from ..compat import compat_str
a71b8d3b 6from ..utils import (
e897bd82
SS
7 JSON_LD_RE,
8 ExtractorError,
ea706726 9 base_url,
29f7c58a 10 clean_html,
a4ec4517 11 determine_ext,
a71b8d3b 12 extract_attributes,
29f7c58a 13 get_element_by_class,
30374f4d 14 merge_dicts,
a71b8d3b 15 parse_duration,
ea1f5e5d 16 smuggle_url,
6857df60 17 try_get,
ea706726 18 url_basename,
e897bd82 19 url_or_none,
ea706726 20 urljoin,
a71b8d3b
RA
21)
22
23
24class ITVIE(InfoExtractor):
f592ff98 25 _VALID_URL = r'https?://(?:www\.)?itv\.com/hub/[^/]+/(?P<id>[0-9a-zA-Z]+)'
4248dad9 26 _GEO_COUNTRIES = ['GB']
3fae11ac 27 _TESTS = [{
ea706726 28 'url': 'https://www.itv.com/hub/plebs/2a1873a0002',
29 'info_dict': {
30 'id': '2a1873a0002',
31 'ext': 'mp4',
32 'title': 'Plebs - The Orgy',
33 'description': 'md5:4d7159af53ebd5b36e8b3ec82a41fdb4',
34 'series': 'Plebs',
35 'season_number': 1,
36 'episode_number': 1,
37 'thumbnail': r're:https?://hubimages\.itv\.com/episode/2_1873_0002'
38 },
39 'params': {
40 # m3u8 download
41 'skip_download': True,
42 },
43 }, {
44 'url': 'https://www.itv.com/hub/the-jonathan-ross-show/2a1166a0209',
a71b8d3b 45 'info_dict': {
ea706726 46 'id': '2a1166a0209',
29f7c58a 47 'ext': 'mp4',
ea706726 48 'title': 'The Jonathan Ross Show - Series 17 - Episode 8',
49 'description': 'md5:3023dcdd375db1bc9967186cdb3f1399',
50 'series': 'The Jonathan Ross Show',
51 'episode_number': 8,
52 'season_number': 17,
53 'thumbnail': r're:https?://hubimages\.itv\.com/episode/2_1873_0002'
a71b8d3b
RA
54 },
55 'params': {
29f7c58a 56 # m3u8 download
a71b8d3b
RA
57 'skip_download': True,
58 },
3fae11ac
S
59 }, {
60 # unavailable via data-playlist-url
61 'url': 'https://www.itv.com/hub/through-the-keyhole/2a2271a0033',
62 'only_matching': True,
c18142da
S
63 }, {
64 # InvalidVodcrid
65 'url': 'https://www.itv.com/hub/james-martins-saturday-morning/2a5159a0034',
66 'only_matching': True,
67 }, {
68 # ContentUnavailable
69 'url': 'https://www.itv.com/hub/whos-doing-the-dishes/2a2898a0024',
70 'only_matching': True,
3fae11ac 71 }]
a71b8d3b 72
ea706726 73 def _generate_api_headers(self, hmac):
74 return merge_dicts({
29f7c58a 75 'Accept': 'application/vnd.itv.vod.playlist.v2+json',
76 'Content-Type': 'application/json',
77 'hmac': hmac.upper(),
ea706726 78 }, self.geo_verification_headers())
79
80 def _call_api(self, video_id, playlist_url, headers, platform_tag, featureset, fatal=True):
81 return self._download_json(
82 playlist_url, video_id, data=json.dumps({
29f7c58a 83 'user': {
84 'itvUserId': '',
85 'entitlements': [],
86 'token': ''
87 },
88 'device': {
89 'manufacturer': 'Safari',
90 'model': '5',
91 'os': {
92 'name': 'Windows NT',
93 'version': '6.1',
94 'type': 'desktop'
95 }
96 },
97 'client': {
98 'version': '4.1',
99 'id': 'browser'
100 },
101 'variantAvailability': {
102 'featureset': {
ea706726 103 'min': featureset,
104 'max': featureset
29f7c58a 105 },
ea706726 106 'platformTag': platform_tag
29f7c58a 107 }
ea706726 108 }).encode(), headers=headers, fatal=fatal)
109
110 def _get_subtitles(self, video_id, variants, ios_playlist_url, headers, *args, **kwargs):
111 subtitles = {}
298bf1d2 112 # Prefer last matching featureset
113 # See: https://github.com/yt-dlp/yt-dlp/issues/986
ea706726 114 platform_tag_subs, featureset_subs = next(
115 ((platform_tag, featureset)
bc8ab44e 116 for platform_tag, featuresets in reversed(list(variants.items())) for featureset in featuresets
ea706726 117 if try_get(featureset, lambda x: x[2]) == 'outband-webvtt'),
118 (None, None))
298bf1d2 119
120 if platform_tag_subs and featureset_subs:
ea706726 121 subs_playlist = self._call_api(
122 video_id, ios_playlist_url, headers, platform_tag_subs, featureset_subs, fatal=False)
123 subs = try_get(subs_playlist, lambda x: x['Playlist']['Video']['Subtitles'], list) or []
124 for sub in subs:
125 if not isinstance(sub, dict):
126 continue
127 href = url_or_none(sub.get('Href'))
128 if not href:
129 continue
130 subtitles.setdefault('en', []).append({'url': href})
131 return subtitles
132
133 def _real_extract(self, url):
134 video_id = self._match_id(url)
135 webpage = self._download_webpage(url, video_id)
136 params = extract_attributes(self._search_regex(
137 r'(?s)(<[^>]+id="video"[^>]*>)', webpage, 'params'))
138 variants = self._parse_json(
139 try_get(params, lambda x: x['data-video-variants'], compat_str) or '{}',
140 video_id, fatal=False)
298bf1d2 141 # Prefer last matching featureset
142 # See: https://github.com/yt-dlp/yt-dlp/issues/986
ea706726 143 platform_tag_video, featureset_video = next(
144 ((platform_tag, featureset)
bc8ab44e 145 for platform_tag, featuresets in reversed(list(variants.items())) for featureset in featuresets
da27aeea 146 if set(try_get(featureset, lambda x: x[:2]) or []) == {'aes', 'hls'}),
ea706726 147 (None, None))
148 if not platform_tag_video or not featureset_video:
149 raise ExtractorError('No downloads available', expected=True, video_id=video_id)
3fae11ac 150
ea706726 151 ios_playlist_url = params.get('data-video-playlist') or params['data-video-id']
152 headers = self._generate_api_headers(params['data-video-hmac'])
153 ios_playlist = self._call_api(
154 video_id, ios_playlist_url, headers, platform_tag_video, featureset_video)
155
156 video_data = try_get(ios_playlist, lambda x: x['Playlist']['Video'], dict) or {}
157 ios_base_url = video_data.get('Base')
3fae11ac 158 formats = []
29f7c58a 159 for media_file in (video_data.get('MediaFiles') or []):
160 href = media_file.get('Href')
161 if not href:
162 continue
163 if ios_base_url:
164 href = ios_base_url + href
165 ext = determine_ext(href)
166 if ext == 'm3u8':
167 formats.extend(self._extract_m3u8_formats(
168 href, video_id, 'mp4', entry_protocol='m3u8_native',
169 m3u8_id='hls', fatal=False))
30374f4d 170 else:
29f7c58a 171 formats.append({
172 'url': href,
30374f4d 173 })
29f7c58a 174 info = self._search_json_ld(webpage, video_id, default={})
175 if not info:
176 json_ld = self._parse_json(self._search_regex(
177 JSON_LD_RE, webpage, 'JSON-LD', '{}',
178 group='json_ld'), video_id, fatal=False)
179 if json_ld and json_ld.get('@type') == 'BreadcrumbList':
180 for ile in (json_ld.get('itemListElement:') or []):
181 item = ile.get('item:') or {}
182 if item.get('@type') == 'TVEpisode':
183 item['@context'] = 'http://schema.org'
184 info = self._json_ld(item, video_id, fatal=False) or {}
185 break
186
ea706726 187 thumbnails = []
188 thumbnail_url = try_get(params, lambda x: x['data-video-posterframe'], compat_str)
189 if thumbnail_url:
190 thumbnails.extend([{
191 'url': thumbnail_url.format(width=1920, height=1080, quality=100, blur=0, bg='false'),
192 'width': 1920,
193 'height': 1080,
194 }, {
195 'url': urljoin(base_url(thumbnail_url), url_basename(thumbnail_url)),
196 'preference': -2
197 }])
198
199 thumbnail_url = self._html_search_meta(['og:image', 'twitter:image'], webpage, default=None)
200 if thumbnail_url:
201 thumbnails.append({
202 'url': thumbnail_url,
203 })
204 self._remove_duplicate_formats(thumbnails)
205
29f7c58a 206 return merge_dicts({
a71b8d3b 207 'id': video_id,
29f7c58a 208 'title': self._html_search_meta(['og:title', 'twitter:title'], webpage),
a71b8d3b 209 'formats': formats,
ea706726 210 'subtitles': self.extract_subtitles(video_id, variants, ios_playlist_url, headers),
29f7c58a 211 'duration': parse_duration(video_data.get('Duration')),
212 'description': clean_html(get_element_by_class('episode-info__synopsis', webpage)),
ea706726 213 'thumbnails': thumbnails
29f7c58a 214 }, info)
ea1f5e5d
S
215
216
217class ITVBTCCIE(InfoExtractor):
3783b5f1 218 _VALID_URL = r'https?://(?:www\.)?itv\.com/(?:news|btcc)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
219 _TESTS = [{
6857df60 220 'url': 'https://www.itv.com/btcc/articles/btcc-2019-brands-hatch-gp-race-action',
ea1f5e5d 221 'info_dict': {
6857df60
W
222 'id': 'btcc-2019-brands-hatch-gp-race-action',
223 'title': 'BTCC 2019: Brands Hatch GP race action',
ea1f5e5d 224 },
85da4055 225 'playlist_count': 12,
3783b5f1 226 }, {
227 'url': 'https://www.itv.com/news/2021-10-27/i-have-to-protect-the-country-says-rishi-sunak-as-uk-faces-interest-rate-hike',
228 'info_dict': {
229 'id': 'i-have-to-protect-the-country-says-rishi-sunak-as-uk-faces-interest-rate-hike',
230 'title': 'md5:6ef054dd9f069330db3dcc66cb772d32'
231 },
232 'playlist_count': 4
233 }]
234 BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/%s/%s_default/index.html?videoId=%s'
ea1f5e5d
S
235
236 def _real_extract(self, url):
237 playlist_id = self._match_id(url)
238
239 webpage = self._download_webpage(url, playlist_id)
240
135dfa2c 241 json_map = try_get(
242 self._search_nextjs_data(webpage, playlist_id),
6857df60
W
243 lambda x: x['props']['pageProps']['article']['body']['content']) or []
244
3783b5f1 245 entries = []
6857df60 246 for video in json_map:
3783b5f1 247 if not any(video['data'].get(attr) == 'Brightcove' for attr in ('name', 'type')):
248 continue
249 video_id = video['data']['id']
250 account_id = video['data']['accountId']
251 player_id = video['data']['playerId']
252 entries.append(self.url_result(
253 smuggle_url(self.BRIGHTCOVE_URL_TEMPLATE % (account_id, player_id, video_id), {
ea1f5e5d
S
254 # ITV does not like some GB IP ranges, so here are some
255 # IP blocks it accepts
256 'geo_ip_blocks': [
257 '193.113.0.0/16', '54.36.162.0/23', '159.65.16.0/21'
258 ],
259 'referrer': url,
260 }),
3783b5f1 261 ie=BrightcoveNewIE.ie_key(), video_id=video_id))
ea1f5e5d
S
262
263 title = self._og_search_title(webpage, fatal=False)
264
265 return self.playlist_result(entries, playlist_id, title)