itv.py 10 KB

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