itv.py 10 KB

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