ign.py 16 KB

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