logo

youtube-dl

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

itv.py (15781B)


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