logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

itv.py (16222B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import sys
  6. from .common import InfoExtractor
  7. from .brightcove import BrightcoveNewIE
  8. from ..compat import (
  9. compat_HTTPError,
  10. compat_integer_types,
  11. compat_kwargs,
  12. compat_urlparse,
  13. )
  14. from ..utils import (
  15. clean_html,
  16. determine_ext,
  17. error_to_compat_str,
  18. extract_attributes,
  19. ExtractorError,
  20. get_element_by_attribute,
  21. int_or_none,
  22. merge_dicts,
  23. parse_duration,
  24. parse_iso8601,
  25. remove_start,
  26. smuggle_url,
  27. strip_or_none,
  28. traverse_obj,
  29. url_or_none,
  30. urljoin,
  31. )
  32. class ITVBaseIE(InfoExtractor):
  33. def _search_nextjs_data(self, webpage, video_id, **kw):
  34. transform_source = kw.pop('transform_source', None)
  35. fatal = kw.pop('fatal', True)
  36. return self._parse_json(
  37. self._search_regex(
  38. r'''<script\b[^>]+\bid=('|")__NEXT_DATA__\1[^>]*>(?P<js>[^<]+)</script>''',
  39. webpage, 'next.js data', group='js', fatal=fatal, **kw),
  40. video_id, transform_source=transform_source, fatal=fatal)
  41. def __handle_request_webpage_error(self, err, video_id=None, errnote=None, fatal=True):
  42. if errnote is False:
  43. return False
  44. if errnote is None:
  45. errnote = 'Unable to download webpage'
  46. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  47. if fatal:
  48. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err, video_id=video_id)
  49. else:
  50. self._downloader.report_warning(errmsg)
  51. return False
  52. @staticmethod
  53. def _vanilla_ua_header():
  54. return {'User-Agent': 'Mozilla/5.0'}
  55. def _download_webpage_handle(self, url, video_id, *args, **kwargs):
  56. # specialised to (a) use vanilla UA (b) detect geo-block
  57. params = self._downloader.params
  58. nkwargs = {}
  59. if (
  60. 'user_agent' not in params
  61. and not any(re.match(r'(?i)user-agent\s*:', h)
  62. for h in (params.get('headers') or []))
  63. and 'User-Agent' not in (kwargs.get('headers') or {})):
  64. kwargs.setdefault('headers', {})
  65. kwargs['headers'] = self._vanilla_ua_header()
  66. nkwargs = kwargs
  67. if kwargs.get('expected_status') is not None:
  68. exp = kwargs['expected_status']
  69. if isinstance(exp, compat_integer_types):
  70. exp = [exp]
  71. if isinstance(exp, (list, tuple)) and 403 not in exp:
  72. kwargs['expected_status'] = [403]
  73. kwargs['expected_status'].extend(exp)
  74. nkwargs = kwargs
  75. else:
  76. kwargs['expected_status'] = 403
  77. nkwargs = kwargs
  78. if nkwargs:
  79. kwargs = compat_kwargs(kwargs)
  80. ret = super(ITVBaseIE, self)._download_webpage_handle(url, video_id, *args, **kwargs)
  81. if ret is False:
  82. return ret
  83. webpage, urlh = ret
  84. if urlh.getcode() == 403:
  85. # geo-block error is like this, with an unnecessary 'Of':
  86. # '{\n "Message" : "Request Originated Outside Of Allowed Geographic Region",\
  87. # \n "TransactionId" : "oas-magni-475082-xbYF0W"\n}'
  88. if '"Request Originated Outside Of Allowed Geographic Region"' in webpage:
  89. self.raise_geo_restricted(countries=['GB'])
  90. ret = self.__handle_request_webpage_error(
  91. compat_HTTPError(urlh.geturl(), 403, 'HTTP Error 403: Forbidden', urlh.headers, urlh),
  92. fatal=kwargs.get('fatal'))
  93. return ret
  94. class ITVIE(ITVBaseIE):
  95. _VALID_URL = r'https?://(?:www\.)?itv\.com/(?:(?P<w>watch)|hub)/[^/]+/(?(w)[\w-]+/)(?P<id>\w+)'
  96. _IE_DESC = 'ITVX'
  97. _TESTS = [{
  98. 'note': 'Hub URLs redirect to ITVX',
  99. 'url': 'https://www.itv.com/hub/liar/2a4547a0012',
  100. 'only_matching': True,
  101. }, {
  102. 'note': 'Hub page unavailable via data-playlist-url (404 now)',
  103. 'url': 'https://www.itv.com/hub/through-the-keyhole/2a2271a0033',
  104. 'only_matching': True,
  105. }, {
  106. 'note': 'Hub page with InvalidVodcrid (404 now)',
  107. 'url': 'https://www.itv.com/hub/james-martins-saturday-morning/2a5159a0034',
  108. 'only_matching': True,
  109. }, {
  110. 'note': 'Hub page with ContentUnavailable (404 now)',
  111. 'url': 'https://www.itv.com/hub/whos-doing-the-dishes/2a2898a0024',
  112. 'only_matching': True,
  113. }, {
  114. 'note': 'ITVX, or itvX, show',
  115. 'url': 'https://www.itv.com/watch/vera/1a7314/1a7314a0014',
  116. 'md5': 'bd0ad666b2c058fffe7d036785880064',
  117. 'info_dict': {
  118. 'id': '1a7314a0014',
  119. 'ext': 'mp4',
  120. 'title': 'Vera - Series 3 - Episode 4 - Prodigal Son',
  121. 'description': 'Vera and her team investigate the fatal stabbing of an ex-Met police officer outside a busy Newcastle nightclub - but there aren\'t many clues.',
  122. 'timestamp': 1653591600,
  123. 'upload_date': '20220526',
  124. 'uploader': 'ITVX',
  125. 'thumbnail': r're:https://\w+\.itv\.com/images/(?:\w+/)+\d+x\d+\?',
  126. 'duration': 5340.8,
  127. 'age_limit': 16,
  128. 'series': 'Vera',
  129. 'series_number': 3,
  130. 'episode': 'Prodigal Son',
  131. 'episode_number': 4,
  132. 'channel': 'ITV3',
  133. 'categories': list,
  134. },
  135. 'params': {
  136. # m3u8 download
  137. # 'skip_download': True,
  138. },
  139. 'skip': 'only available in UK',
  140. }, {
  141. 'note': 'Latest ITV news bulletin: details change daily',
  142. 'url': 'https://www.itv.com/watch/news/varies-but-is-not-checked/6js5d0f',
  143. 'info_dict': {
  144. 'id': '6js5d0f',
  145. 'ext': 'mp4',
  146. 'title': r're:The latest ITV News headlines - \S.+',
  147. 'description': r'''re:.* today's top stories from the ITV News team.$''',
  148. 'timestamp': int,
  149. 'upload_date': r're:2\d\d\d(?:0[1-9]|1[0-2])(?:[012][1-9]|3[01])',
  150. 'uploader': 'ITVX',
  151. 'thumbnail': r're:https://images\.ctfassets\.net/(?:\w+/)+[\w.]+\.(?:jpg|png)',
  152. 'duration': float,
  153. 'age_limit': None,
  154. },
  155. 'params': {
  156. # variable download
  157. # 'skip_download': True,
  158. },
  159. 'skip': 'only available in UK',
  160. }
  161. ]
  162. def _og_extract(self, webpage, require_title=False):
  163. return {
  164. 'title': self._og_search_title(webpage, fatal=require_title),
  165. 'description': self._og_search_description(webpage, default=None),
  166. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  167. 'uploader': self._og_search_property('site_name', webpage, default=None),
  168. }
  169. def _real_extract(self, url):
  170. video_id = self._match_id(url)
  171. webpage = self._download_webpage(url, video_id)
  172. # now quite different params!
  173. params = extract_attributes(self._search_regex(
  174. r'''(<[^>]+\b(?:class|data-testid)\s*=\s*("|')genie-container\2[^>]*>)''',
  175. webpage, 'params'))
  176. ios_playlist_url = traverse_obj(
  177. params, 'data-video-id', 'data-video-playlist',
  178. get_all=False, expected_type=url_or_none)
  179. headers = self.geo_verification_headers()
  180. headers.update({
  181. 'Accept': 'application/vnd.itv.vod.playlist.v2+json',
  182. 'Content-Type': 'application/json',
  183. })
  184. ios_playlist = self._download_json(
  185. ios_playlist_url, video_id, data=json.dumps({
  186. 'user': {
  187. 'entitlements': [],
  188. },
  189. 'device': {
  190. 'manufacturer': 'Mobile Safari',
  191. 'model': '5.1',
  192. 'os': {
  193. 'name': 'iOS',
  194. 'version': '5.0',
  195. 'type': ' mobile'
  196. }
  197. },
  198. 'client': {
  199. 'version': '4.1',
  200. 'id': 'browser',
  201. 'supportsAdPods': True,
  202. 'service': 'itv.x',
  203. 'appversion': '2.43.28',
  204. },
  205. 'variantAvailability': {
  206. 'player': 'hls',
  207. 'featureset': {
  208. 'min': ['hls', 'aes', 'outband-webvtt'],
  209. 'max': ['hls', 'aes', 'outband-webvtt']
  210. },
  211. 'platformTag': 'mobile'
  212. }
  213. }).encode(), headers=headers)
  214. video_data = ios_playlist['Playlist']['Video']
  215. ios_base_url = traverse_obj(video_data, 'Base', expected_type=url_or_none)
  216. media_url = (
  217. (lambda u: url_or_none(urljoin(ios_base_url, u)))
  218. if ios_base_url else url_or_none)
  219. formats = []
  220. for media_file in traverse_obj(video_data, 'MediaFiles', expected_type=list) or []:
  221. href = traverse_obj(media_file, 'Href', expected_type=media_url)
  222. if not href:
  223. continue
  224. ext = determine_ext(href)
  225. if ext == 'm3u8':
  226. formats.extend(self._extract_m3u8_formats(
  227. href, video_id, 'mp4', entry_protocol='m3u8',
  228. m3u8_id='hls', fatal=False))
  229. else:
  230. formats.append({
  231. 'url': href,
  232. })
  233. self._sort_formats(formats)
  234. for f in formats:
  235. f.setdefault('http_headers', {})
  236. f['http_headers'].update(self._vanilla_ua_header())
  237. subtitles = {}
  238. for sub in traverse_obj(video_data, 'Subtitles', expected_type=list) or []:
  239. href = traverse_obj(sub, 'Href', expected_type=url_or_none)
  240. if not href:
  241. continue
  242. subtitles.setdefault('en', []).append({
  243. 'url': href,
  244. 'ext': determine_ext(href, 'vtt'),
  245. })
  246. next_data = self._search_nextjs_data(webpage, video_id, fatal=False, default='{}')
  247. video_data.update(traverse_obj(next_data, ('props', 'pageProps', ('title', 'episode')), expected_type=dict)[0] or {})
  248. title = traverse_obj(video_data, 'headerTitle', 'episodeTitle')
  249. info = self._og_extract(webpage, require_title=not title)
  250. tn = info.pop('thumbnail', None)
  251. if tn:
  252. info['thumbnails'] = [{'url': tn}]
  253. # num. episode title
  254. num_ep_title = video_data.get('numberedEpisodeTitle')
  255. if not num_ep_title:
  256. num_ep_title = clean_html(get_element_by_attribute('data-testid', 'episode-hero-description-strong', webpage))
  257. num_ep_title = num_ep_title and num_ep_title.rstrip(' -')
  258. ep_title = strip_or_none(
  259. video_data.get('episodeTitle')
  260. or (num_ep_title.split('.', 1)[-1] if num_ep_title else None))
  261. title = title or re.sub(r'\s+-\s+ITVX$', '', info['title'])
  262. if ep_title and ep_title != title:
  263. title = title + ' - ' + ep_title
  264. def get_thumbnails():
  265. tns = []
  266. for w, x in (traverse_obj(video_data, ('imagePresets'), expected_type=dict) or {}).items():
  267. if isinstance(x, dict):
  268. for y, z in x.items():
  269. tns.append({'id': w + '_' + y, 'url': z})
  270. return tns or None
  271. video_str = lambda *x: traverse_obj(
  272. video_data, *x, get_all=False, expected_type=strip_or_none)
  273. return merge_dicts({
  274. 'id': video_id,
  275. 'title': title,
  276. 'formats': formats,
  277. 'subtitles': subtitles,
  278. # parsing hh:mm:ss:nnn not yet patched
  279. 'duration': parse_duration(re.sub(r'(\d{2})(:)(\d{3}$)', r'\1.\3', video_data.get('Duration') or '')),
  280. 'description': video_str('synopsis'),
  281. 'timestamp': traverse_obj(video_data, 'broadcastDateTime', 'dateTime', expected_type=parse_iso8601),
  282. 'thumbnails': get_thumbnails(),
  283. 'series': video_str('showTitle', 'programmeTitle'),
  284. 'series_number': int_or_none(video_data.get('seriesNumber')),
  285. 'episode': ep_title,
  286. 'episode_number': int_or_none((num_ep_title or '').split('.')[0]),
  287. 'channel': video_str('channel'),
  288. 'categories': traverse_obj(video_data, ('categories', 'formatted'), expected_type=list),
  289. 'age_limit': {False: 16, True: 0}.get(video_data.get('isChildrenCategory')),
  290. }, info)
  291. class ITVBTCCIE(ITVBaseIE):
  292. _VALID_URL = r'https?://(?:www\.)?itv\.com/(?!(?:watch|hub)/)(?:[^/]+/)+(?P<id>[^/?#&]+)'
  293. _IE_DESC = 'ITV articles: News, British Touring Car Championship'
  294. _TESTS = [{
  295. 'note': 'British Touring Car Championship',
  296. 'url': 'https://www.itv.com/btcc/articles/btcc-2018-all-the-action-from-brands-hatch',
  297. 'info_dict': {
  298. 'id': 'btcc-2018-all-the-action-from-brands-hatch',
  299. 'title': 'BTCC 2018: All the action from Brands Hatch',
  300. },
  301. 'playlist_mincount': 9,
  302. }, {
  303. 'note': 'redirects to /btcc/articles/...',
  304. 'url': 'http://www.itv.com/btcc/races/btcc-2018-all-the-action-from-brands-hatch',
  305. 'only_matching': True,
  306. }, {
  307. 'note': 'news article',
  308. 'url': 'https://www.itv.com/news/wales/2020-07-23/sean-fletcher-shows-off-wales-coastline-in-new-itv-series-as-british-tourists-opt-for-staycations',
  309. 'info_dict': {
  310. 'id': 'sean-fletcher-shows-off-wales-coastline-in-new-itv-series-as-british-tourists-opt-for-staycations',
  311. 'title': '''Sean Fletcher on why Wales' coastline should be your 'staycation' destination | ITV News''',
  312. },
  313. 'playlist_mincount': 1,
  314. }]
  315. # should really be a class var of the BC IE
  316. BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/%s/%s_default/index.html?videoId=%s'
  317. BRIGHTCOVE_ACCOUNT = '1582188683001'
  318. BRIGHTCOVE_PLAYER = 'HkiHLnNRx'
  319. def _real_extract(self, url):
  320. playlist_id = self._match_id(url)
  321. webpage, urlh = self._download_webpage_handle(url, playlist_id)
  322. link = compat_urlparse.urlparse(urlh.geturl()).path.strip('/')
  323. next_data = self._search_nextjs_data(webpage, playlist_id, fatal=False, default='{}')
  324. path_prefix = compat_urlparse.urlparse(next_data.get('assetPrefix') or '').path.strip('/')
  325. link = remove_start(link, path_prefix).strip('/')
  326. content = traverse_obj(
  327. next_data, ('props', 'pageProps', Ellipsis),
  328. expected_type=lambda x: x if x['link'] == link else None,
  329. get_all=False, default={})
  330. content = traverse_obj(
  331. content, ('body', 'content', Ellipsis, 'data'),
  332. expected_type=lambda x: x if x.get('name') == 'Brightcove' or x.get('type') == 'Brightcove' else None)
  333. contraband = {
  334. # ITV does not like some GB IP ranges, so here are some
  335. # IP blocks it accepts
  336. 'geo_ip_blocks': [
  337. '193.113.0.0/16', '54.36.162.0/23', '159.65.16.0/21'
  338. ],
  339. 'referrer': urlh.geturl(),
  340. }
  341. def entries():
  342. for data in content or []:
  343. video_id = data.get('id')
  344. if not video_id:
  345. continue
  346. account = data.get('accountId') or self.BRIGHTCOVE_ACCOUNT
  347. player = data.get('playerId') or self.BRIGHTCOVE_PLAYER
  348. yield self.url_result(
  349. smuggle_url(self.BRIGHTCOVE_URL_TEMPLATE % (account, player, video_id), contraband),
  350. ie=BrightcoveNewIE.ie_key(), video_id=video_id)
  351. # obsolete ?
  352. for video_id in re.findall(r'''data-video-id=["'](\d+)''', webpage):
  353. yield self.url_result(
  354. smuggle_url(self.BRIGHTCOVE_URL_TEMPLATE % (self.BRIGHTCOVE_ACCOUNT, self.BRIGHTCOVE_PLAYER, video_id), contraband),
  355. ie=BrightcoveNewIE.ie_key(), video_id=video_id)
  356. title = self._og_search_title(webpage, fatal=False)
  357. return self.playlist_result(entries(), playlist_id, title)