logo

youtube-dl

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

ign.py (16256B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_filter as filter,
  7. compat_HTTPError,
  8. compat_parse_qs,
  9. compat_urlparse,
  10. )
  11. from ..utils import (
  12. determine_ext,
  13. error_to_compat_str,
  14. extract_attributes,
  15. ExtractorError,
  16. int_or_none,
  17. merge_dicts,
  18. orderedSet,
  19. parse_iso8601,
  20. strip_or_none,
  21. traverse_obj,
  22. url_or_none,
  23. urljoin,
  24. )
  25. class IGNBaseIE(InfoExtractor):
  26. def _call_api(self, slug):
  27. return self._download_json(
  28. 'http://apis.ign.com/{0}/v3/{0}s/slug/{1}'.format(self._PAGE_TYPE, slug), slug)
  29. def _checked_call_api(self, slug):
  30. try:
  31. return self._call_api(slug)
  32. except ExtractorError as e:
  33. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
  34. e.cause.args = e.cause.args or [
  35. e.cause.geturl(), e.cause.getcode(), e.cause.reason]
  36. raise ExtractorError(
  37. 'Content not found: expired?', cause=e.cause,
  38. expected=True)
  39. raise
  40. def _extract_video_info(self, video, fatal=True):
  41. video_id = video['videoId']
  42. formats = []
  43. refs = traverse_obj(video, 'refs', expected_type=dict) or {}
  44. m3u8_url = url_or_none(refs.get('m3uUrl'))
  45. if m3u8_url:
  46. formats.extend(self._extract_m3u8_formats(
  47. m3u8_url, video_id, 'mp4', 'm3u8_native',
  48. m3u8_id='hls', fatal=False))
  49. f4m_url = url_or_none(refs.get('f4mUrl'))
  50. if f4m_url:
  51. formats.extend(self._extract_f4m_formats(
  52. f4m_url, video_id, f4m_id='hds', fatal=False))
  53. for asset in (video.get('assets') or []):
  54. asset_url = url_or_none(asset.get('url'))
  55. if not asset_url:
  56. continue
  57. formats.append({
  58. 'url': asset_url,
  59. 'tbr': int_or_none(asset.get('bitrate'), 1000),
  60. 'fps': int_or_none(asset.get('frame_rate')),
  61. 'height': int_or_none(asset.get('height')),
  62. 'width': int_or_none(asset.get('width')),
  63. })
  64. mezzanine_url = traverse_obj(
  65. video, ('system', 'mezzanineUrl'), expected_type=url_or_none)
  66. if mezzanine_url:
  67. formats.append({
  68. 'ext': determine_ext(mezzanine_url, 'mp4'),
  69. 'format_id': 'mezzanine',
  70. 'preference': 1,
  71. 'url': mezzanine_url,
  72. })
  73. if formats or fatal:
  74. self._sort_formats(formats)
  75. else:
  76. return
  77. thumbnails = traverse_obj(
  78. video, ('thumbnails', Ellipsis, {'url': 'url'}), expected_type=url_or_none)
  79. tags = traverse_obj(
  80. video, ('tags', Ellipsis, 'displayName'),
  81. expected_type=lambda x: x.strip() or None)
  82. metadata = traverse_obj(video, 'metadata', expected_type=dict) or {}
  83. title = traverse_obj(
  84. metadata, 'longTitle', 'title', 'name',
  85. expected_type=lambda x: x.strip() or None)
  86. return {
  87. 'id': video_id,
  88. 'title': title,
  89. 'description': strip_or_none(metadata.get('description')),
  90. 'timestamp': parse_iso8601(metadata.get('publishDate')),
  91. 'duration': int_or_none(metadata.get('duration')),
  92. 'thumbnails': thumbnails,
  93. 'formats': formats,
  94. 'tags': tags,
  95. }
  96. # yt-dlp shim
  97. @classmethod
  98. def _extract_from_webpage(cls, url, webpage):
  99. for embed_url in orderedSet(
  100. cls._extract_embed_urls(url, webpage) or [], lazy=True):
  101. yield cls.url_result(embed_url, None if cls._VALID_URL is False else cls)
  102. class IGNIE(IGNBaseIE):
  103. """
  104. Extractor for some of the IGN sites, like www.ign.com, es.ign.com de.ign.com.
  105. Some videos of it.ign.com are also supported
  106. """
  107. _VIDEO_PATH_RE = r'/(?:\d{4}/\d{2}/\d{2}/)?(?P<id>.+?)'
  108. _PLAYLIST_PATH_RE = r'(?:/?\?(?P<filt>[^&#]+))?'
  109. _VALID_URL = (
  110. r'https?://(?:.+?\.ign|www\.pcmag)\.com/videos(?:%s)'
  111. % '|'.join((_VIDEO_PATH_RE + r'(?:[/?&#]|$)', _PLAYLIST_PATH_RE)))
  112. IE_NAME = 'ign.com'
  113. _PAGE_TYPE = 'video'
  114. _TESTS = [{
  115. 'url': 'http://www.ign.com/videos/2013/06/05/the-last-of-us-review',
  116. 'md5': 'd2e1586d9987d40fad7867bf96a018ea',
  117. 'info_dict': {
  118. 'id': '8f862beef863986b2785559b9e1aa599',
  119. 'ext': 'mp4',
  120. 'title': 'The Last of Us Review',
  121. 'description': 'md5:c8946d4260a4d43a00d5ae8ed998870c',
  122. 'timestamp': 1370440800,
  123. 'upload_date': '20130605',
  124. 'tags': 'count:9',
  125. },
  126. 'params': {
  127. 'nocheckcertificate': True,
  128. },
  129. }, {
  130. 'url': 'http://www.pcmag.com/videos/2015/01/06/010615-whats-new-now-is-gogo-snooping-on-your-data',
  131. 'md5': 'f1581a6fe8c5121be5b807684aeac3f6',
  132. 'info_dict': {
  133. 'id': 'ee10d774b508c9b8ec07e763b9125b91',
  134. 'ext': 'mp4',
  135. 'title': 'What\'s New Now: Is GoGo Snooping on Your Data?',
  136. 'description': 'md5:817a20299de610bd56f13175386da6fa',
  137. 'timestamp': 1420571160,
  138. 'upload_date': '20150106',
  139. 'tags': 'count:4',
  140. },
  141. 'skip': '404 Not Found',
  142. }, {
  143. 'url': 'https://www.ign.com/videos/is-a-resident-evil-4-remake-on-the-way-ign-daily-fix',
  144. 'only_matching': True,
  145. }]
  146. @classmethod
  147. def _extract_embed_urls(cls, url, webpage):
  148. grids = re.findall(
  149. r'''(?s)<section\b[^>]+\bclass\s*=\s*['"](?:[\w-]+\s+)*?content-feed-grid(?!\B|-)[^>]+>(.+?)</section[^>]*>''',
  150. webpage)
  151. return filter(None,
  152. (urljoin(url, m.group('path')) for m in re.finditer(
  153. r'''<a\b[^>]+\bhref\s*=\s*('|")(?P<path>/videos%s)\1'''
  154. % cls._VIDEO_PATH_RE, grids[0] if grids else '')))
  155. def _real_extract(self, url):
  156. m = re.match(self._VALID_URL, url)
  157. display_id = m.group('id')
  158. if display_id:
  159. return self._extract_video(url, display_id)
  160. display_id = m.group('filt') or 'all'
  161. return self._extract_playlist(url, display_id)
  162. def _extract_playlist(self, url, display_id):
  163. webpage = self._download_webpage(url, display_id)
  164. return self.playlist_result(
  165. (self.url_result(u, ie=self.ie_key())
  166. for u in self._extract_embed_urls(url, webpage)),
  167. playlist_id=display_id)
  168. def _extract_video(self, url, display_id):
  169. display_id = self._match_id(url)
  170. video = self._checked_call_api(display_id)
  171. info = self._extract_video_info(video)
  172. return merge_dicts({
  173. 'display_id': display_id,
  174. }, info)
  175. class IGNVideoIE(IGNBaseIE):
  176. _VALID_URL = r'https?://.+?\.ign\.com/(?:[a-z]{2}/)?[^/]+/(?P<id>\d+)/(?:video|trailer)/'
  177. _TESTS = [{
  178. 'url': 'http://me.ign.com/en/videos/112203/video/how-hitman-aims-to-be-different-than-every-other-s',
  179. 'md5': 'dd9aca7ed2657c4e118d8b261e5e9de1',
  180. 'info_dict': {
  181. 'id': 'e9be7ea899a9bbfc0674accc22a36cc8',
  182. 'ext': 'mp4',
  183. 'title': 'How Hitman Aims to Be Different Than Every Other Stealth Game - NYCC 2015',
  184. 'description': 'Taking out assassination targets in Hitman has never been more stylish.',
  185. 'timestamp': 1444665600,
  186. 'upload_date': '20151012',
  187. },
  188. 'expected_warnings': ['HTTP Error 400: Bad Request'],
  189. }, {
  190. 'url': 'http://me.ign.com/ar/angry-birds-2/106533/video/lrd-ldyy-lwl-lfylm-angry-birds',
  191. 'only_matching': True,
  192. }, {
  193. # Youtube embed
  194. 'url': 'https://me.ign.com/ar/ratchet-clank-rift-apart/144327/trailer/embed',
  195. 'only_matching': True,
  196. }, {
  197. # Twitter embed
  198. 'url': 'http://adria.ign.com/sherlock-season-4/9687/trailer/embed',
  199. 'only_matching': True,
  200. }, {
  201. # Vimeo embed
  202. 'url': 'https://kr.ign.com/bic-2018/3307/trailer/embed',
  203. 'only_matching': True,
  204. }]
  205. def _real_extract(self, url):
  206. video_id = self._match_id(url)
  207. parsed_url = compat_urlparse.urlparse(url)
  208. embed_url = compat_urlparse.urlunparse(
  209. parsed_url._replace(path=parsed_url.path.rsplit('/', 1)[0] + '/embed'))
  210. webpage, urlh = self._download_webpage_handle(embed_url, video_id)
  211. new_url = urlh.geturl()
  212. ign_url = compat_parse_qs(
  213. compat_urlparse.urlparse(new_url).query).get('url', [None])[-1]
  214. if ign_url:
  215. return self.url_result(ign_url, IGNIE.ie_key())
  216. video = self._search_regex(r'(<div\b[^>]+\bdata-video-id\s*=\s*[^>]+>)', webpage, 'video element', fatal=False)
  217. if not video:
  218. if new_url == url:
  219. raise ExtractorError('Redirect loop: ' + url)
  220. return self.url_result(new_url)
  221. video = extract_attributes(video)
  222. video_data = video.get('data-settings') or '{}'
  223. video_data = self._parse_json(video_data, video_id)['video']
  224. info = self._extract_video_info(video_data)
  225. return merge_dicts({
  226. 'display_id': video_id,
  227. }, info)
  228. class IGNArticleIE(IGNBaseIE):
  229. _VALID_URL = r'https?://.+?\.ign\.com/(?:articles(?:/\d{4}/\d{2}/\d{2})?|(?:[a-z]{2}/)?(?:[\w-]+/)*?feature/\d+)/(?P<id>[^/?&#]+)'
  230. _PAGE_TYPE = 'article'
  231. _TESTS = [{
  232. 'url': 'http://me.ign.com/en/feature/15775/100-little-things-in-gta-5-that-will-blow-your-mind',
  233. 'info_dict': {
  234. 'id': '72113',
  235. 'title': '100 Little Things in GTA 5 That Will Blow Your Mind',
  236. },
  237. 'playlist': [
  238. {
  239. 'info_dict': {
  240. 'id': '5ebbd138523268b93c9141af17bec937',
  241. 'ext': 'mp4',
  242. 'title': 'Grand Theft Auto V Video Review',
  243. 'description': 'Rockstar drops the mic on this generation of games. Watch our review of the masterly Grand Theft Auto V.',
  244. 'timestamp': 1379339880,
  245. 'upload_date': '20130916',
  246. },
  247. },
  248. {
  249. 'info_dict': {
  250. 'id': '638672ee848ae4ff108df2a296418ee2',
  251. 'ext': 'mp4',
  252. 'title': 'GTA 5 In Slow Motion',
  253. 'description': 'The twisted beauty of GTA 5 in stunning slow motion.',
  254. 'timestamp': 1386878820,
  255. 'upload_date': '20131212',
  256. },
  257. },
  258. ],
  259. 'params': {
  260. 'skip_download': True,
  261. },
  262. 'expected_warnings': ['Backend fetch failed'],
  263. }, {
  264. 'url': 'http://www.ign.com/articles/2014/08/15/rewind-theater-wild-trailer-gamescom-2014?watch',
  265. 'info_dict': {
  266. 'id': '53ee806780a81ec46e0790f8',
  267. 'title': 'Rewind Theater - Wild Trailer Gamescom 2014',
  268. },
  269. 'playlist_count': 1,
  270. 'expected_warnings': ['Backend fetch failed'],
  271. }, {
  272. # videoId pattern
  273. 'url': 'http://www.ign.com/articles/2017/06/08/new-ducktales-short-donalds-birthday-doesnt-go-as-planned',
  274. 'only_matching': True,
  275. }, {
  276. # Youtube embed
  277. 'url': 'https://www.ign.com/articles/2021-mvp-named-in-puppy-bowl-xvii',
  278. 'only_matching': True,
  279. }, {
  280. # IMDB embed
  281. 'url': 'https://www.ign.com/articles/2014/08/07/sons-of-anarchy-final-season-trailer',
  282. 'only_matching': True,
  283. }, {
  284. # Facebook embed
  285. 'url': 'https://www.ign.com/articles/2017/09/20/marvels-the-punisher-watch-the-new-trailer-for-the-netflix-series',
  286. 'only_matching': True,
  287. }, {
  288. # Brightcove embed
  289. 'url': 'https://www.ign.com/articles/2016/01/16/supergirl-goes-flying-with-martian-manhunter-in-new-clip',
  290. 'only_matching': True,
  291. }]
  292. def _checked_call_api(self, slug):
  293. try:
  294. return self._call_api(slug)
  295. except ExtractorError as e:
  296. if isinstance(e.cause, compat_HTTPError):
  297. e.cause.args = e.cause.args or [
  298. e.cause.geturl(), e.cause.getcode(), e.cause.reason]
  299. if e.cause.code == 404:
  300. raise ExtractorError(
  301. 'Content not found: expired?', cause=e.cause,
  302. expected=True)
  303. elif e.cause.code == 503:
  304. self.report_warning(error_to_compat_str(e.cause))
  305. return
  306. raise
  307. def _search_nextjs_data(self, webpage, video_id, **kw):
  308. return self._parse_json(
  309. self._search_regex(
  310. r'(?s)<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>([^<]+)</script>',
  311. webpage, 'next.js data', **kw),
  312. video_id, **kw)
  313. def _real_extract(self, url):
  314. display_id = self._match_id(url)
  315. article = self._checked_call_api(display_id)
  316. if article:
  317. # obsolete ?
  318. def entries():
  319. media_url = traverse_obj(
  320. article, ('mediaRelations', 0, 'media', 'metadata', 'url'),
  321. expected_type=url_or_none)
  322. if media_url:
  323. yield self.url_result(media_url, IGNIE.ie_key())
  324. for content in (article.get('content') or []):
  325. for video_url in re.findall(r'(?:\[(?:ignvideo\s+url|youtube\s+clip_id)|<iframe[^>]+src)="([^"]+)"', content):
  326. if url_or_none(video_url):
  327. yield self.url_result(video_url)
  328. return self.playlist_result(
  329. entries(), article.get('articleId'),
  330. traverse_obj(
  331. article, ('metadata', 'headline'),
  332. expected_type=lambda x: x.strip() or None))
  333. webpage = self._download_webpage(url, display_id)
  334. playlist_id = self._html_search_meta('dable:item_id', webpage, default=None)
  335. if playlist_id:
  336. def entries():
  337. for m in re.finditer(
  338. r'''(?s)<object\b[^>]+\bclass\s*=\s*("|')ign-videoplayer\1[^>]*>(?P<params>.+?)</object''',
  339. webpage):
  340. flashvars = self._search_regex(
  341. r'''(<param\b[^>]+\bname\s*=\s*("|')flashvars\2[^>]*>)''',
  342. m.group('params'), 'flashvars', default='')
  343. flashvars = compat_parse_qs(extract_attributes(flashvars).get('value') or '')
  344. v_url = url_or_none((flashvars.get('url') or [None])[-1])
  345. if v_url:
  346. yield self.url_result(v_url)
  347. else:
  348. playlist_id = self._search_regex(
  349. r'''\bdata-post-id\s*=\s*("|')(?P<id>[\da-f]+)\1''',
  350. webpage, 'id', group='id', default=None)
  351. nextjs_data = self._search_nextjs_data(webpage, display_id)
  352. def entries():
  353. for player in traverse_obj(
  354. nextjs_data,
  355. ('props', 'apolloState', 'ROOT_QUERY', lambda k, _: k.startswith('videoPlayerProps('), '__ref')):
  356. # skip promo links (which may not always be served, eg GH CI servers)
  357. if traverse_obj(nextjs_data,
  358. ('props', 'apolloState', player.replace('PlayerProps', 'ModernContent')),
  359. expected_type=dict):
  360. continue
  361. video = traverse_obj(nextjs_data, ('props', 'apolloState', player), expected_type=dict) or {}
  362. info = self._extract_video_info(video, fatal=False)
  363. if info:
  364. yield merge_dicts({
  365. 'display_id': display_id,
  366. }, info)
  367. return self.playlist_result(
  368. entries(), playlist_id or display_id,
  369. re.sub(r'\s+-\s+IGN\s*$', '', self._og_search_title(webpage, default='')) or None)