]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/itv.py
Update to ytdl-2021.01.03
[yt-dlp.git] / youtube_dlc / extractor / itv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6
7 from .common import InfoExtractor
8 from .brightcove import BrightcoveNewIE
9 from ..utils import (
10 clean_html,
11 determine_ext,
12 extract_attributes,
13 get_element_by_class,
14 JSON_LD_RE,
15 merge_dicts,
16 parse_duration,
17 smuggle_url,
18 try_get,
19 url_or_none,
20 )
21
22
23 class ITVIE(InfoExtractor):
24 _VALID_URL = r'https?://(?:www\.)?itv\.com/hub/[^/]+/(?P<id>[0-9a-zA-Z]+)'
25 _GEO_COUNTRIES = ['GB']
26 _TESTS = [{
27 'url': 'https://www.itv.com/hub/liar/2a4547a0012',
28 'info_dict': {
29 'id': '2a4547a0012',
30 'ext': 'mp4',
31 'title': 'Liar - Series 2 - Episode 6',
32 'description': 'md5:d0f91536569dec79ea184f0a44cca089',
33 'series': 'Liar',
34 'season_number': 2,
35 'episode_number': 6,
36 },
37 'params': {
38 # m3u8 download
39 'skip_download': True,
40 },
41 }, {
42 # unavailable via data-playlist-url
43 'url': 'https://www.itv.com/hub/through-the-keyhole/2a2271a0033',
44 'only_matching': True,
45 }, {
46 # InvalidVodcrid
47 'url': 'https://www.itv.com/hub/james-martins-saturday-morning/2a5159a0034',
48 'only_matching': True,
49 }, {
50 # ContentUnavailable
51 'url': 'https://www.itv.com/hub/whos-doing-the-dishes/2a2898a0024',
52 'only_matching': True,
53 }]
54
55 def _real_extract(self, url):
56 video_id = self._match_id(url)
57 webpage = self._download_webpage(url, video_id)
58 params = extract_attributes(self._search_regex(
59 r'(?s)(<[^>]+id="video"[^>]*>)', webpage, 'params'))
60
61 ios_playlist_url = params.get('data-video-playlist') or params['data-video-id']
62 hmac = params['data-video-hmac']
63 headers = self.geo_verification_headers()
64 headers.update({
65 'Accept': 'application/vnd.itv.vod.playlist.v2+json',
66 'Content-Type': 'application/json',
67 'hmac': hmac.upper(),
68 })
69 ios_playlist = self._download_json(
70 ios_playlist_url, video_id, data=json.dumps({
71 'user': {
72 'itvUserId': '',
73 'entitlements': [],
74 'token': ''
75 },
76 'device': {
77 'manufacturer': 'Safari',
78 'model': '5',
79 'os': {
80 'name': 'Windows NT',
81 'version': '6.1',
82 'type': 'desktop'
83 }
84 },
85 'client': {
86 'version': '4.1',
87 'id': 'browser'
88 },
89 'variantAvailability': {
90 'featureset': {
91 'min': ['hls', 'aes', 'outband-webvtt'],
92 'max': ['hls', 'aes', 'outband-webvtt']
93 },
94 'platformTag': 'dotcom'
95 }
96 }).encode(), headers=headers)
97 video_data = ios_playlist['Playlist']['Video']
98 ios_base_url = video_data.get('Base')
99
100 formats = []
101 for media_file in (video_data.get('MediaFiles') or []):
102 href = media_file.get('Href')
103 if not href:
104 continue
105 if ios_base_url:
106 href = ios_base_url + href
107 ext = determine_ext(href)
108 if ext == 'm3u8':
109 formats.extend(self._extract_m3u8_formats(
110 href, video_id, 'mp4', entry_protocol='m3u8_native',
111 m3u8_id='hls', fatal=False))
112 else:
113 formats.append({
114 'url': href,
115 })
116 self._sort_formats(formats)
117
118 subtitles = {}
119 subs = video_data.get('Subtitles') or []
120 for sub in subs:
121 if not isinstance(sub, dict):
122 continue
123 href = url_or_none(sub.get('Href'))
124 if not href:
125 continue
126 subtitles.setdefault('en', []).append({
127 'url': href,
128 'ext': determine_ext(href, 'vtt'),
129 })
130
131 info = self._search_json_ld(webpage, video_id, default={})
132 if not info:
133 json_ld = self._parse_json(self._search_regex(
134 JSON_LD_RE, webpage, 'JSON-LD', '{}',
135 group='json_ld'), video_id, fatal=False)
136 if json_ld and json_ld.get('@type') == 'BreadcrumbList':
137 for ile in (json_ld.get('itemListElement:') or []):
138 item = ile.get('item:') or {}
139 if item.get('@type') == 'TVEpisode':
140 item['@context'] = 'http://schema.org'
141 info = self._json_ld(item, video_id, fatal=False) or {}
142 break
143
144 return merge_dicts({
145 'id': video_id,
146 'title': self._html_search_meta(['og:title', 'twitter:title'], webpage),
147 'formats': formats,
148 'subtitles': subtitles,
149 'duration': parse_duration(video_data.get('Duration')),
150 'description': clean_html(get_element_by_class('episode-info__synopsis', webpage)),
151 }, info)
152
153
154 class ITVBTCCIE(InfoExtractor):
155 _VALID_URL = r'https?://(?:www\.)?itv\.com/btcc/(?:[^/]+/)*(?P<id>[^/?#&]+)'
156 _TEST = {
157 'url': 'https://www.itv.com/btcc/articles/btcc-2019-brands-hatch-gp-race-action',
158 'info_dict': {
159 'id': 'btcc-2019-brands-hatch-gp-race-action',
160 'title': 'BTCC 2019: Brands Hatch GP race action',
161 },
162 'playlist_count': 12,
163 }
164 BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/1582188683001/HkiHLnNRx_default/index.html?videoId=%s'
165
166 def _real_extract(self, url):
167 playlist_id = self._match_id(url)
168
169 webpage = self._download_webpage(url, playlist_id)
170
171 json_map = try_get(self._parse_json(self._html_search_regex(
172 '(?s)<script[^>]+id=[\'"]__NEXT_DATA__[^>]*>([^<]+)</script>', webpage, 'json_map'), playlist_id),
173 lambda x: x['props']['pageProps']['article']['body']['content']) or []
174
175 # Discard empty objects
176 video_ids = []
177 for video in json_map:
178 if video['data'].get('id'):
179 video_ids.append(video['data']['id'])
180
181 entries = [
182 self.url_result(
183 smuggle_url(self.BRIGHTCOVE_URL_TEMPLATE % video_id, {
184 # ITV does not like some GB IP ranges, so here are some
185 # IP blocks it accepts
186 'geo_ip_blocks': [
187 '193.113.0.0/16', '54.36.162.0/23', '159.65.16.0/21'
188 ],
189 'referrer': url,
190 }),
191 ie=BrightcoveNewIE.ie_key(), video_id=video_id)
192 for video_id in video_ids]
193
194 title = self._og_search_title(webpage, fatal=False)
195
196 return self.playlist_result(entries, playlist_id, title)