logo

youtube-dl

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

instagram.py (17625B)


  1. from __future__ import unicode_literals
  2. import itertools
  3. import hashlib
  4. import json
  5. import re
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_str,
  9. compat_HTTPError,
  10. )
  11. from ..utils import (
  12. ExtractorError,
  13. float_or_none,
  14. get_element_by_attribute,
  15. int_or_none,
  16. lowercase_escape,
  17. std_headers,
  18. try_get,
  19. url_or_none,
  20. )
  21. class InstagramIE(InfoExtractor):
  22. _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
  23. _TESTS = [{
  24. 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
  25. 'md5': '0d2da106a9d2631273e192b372806516',
  26. 'info_dict': {
  27. 'id': 'aye83DjauH',
  28. 'ext': 'mp4',
  29. 'title': 'Video by naomipq',
  30. 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
  31. 'thumbnail': r're:^https?://.*\.jpg',
  32. 'duration': 0,
  33. 'timestamp': 1371748545,
  34. 'upload_date': '20130620',
  35. 'uploader_id': 'naomipq',
  36. 'uploader': 'B E A U T Y F O R A S H E S',
  37. 'like_count': int,
  38. 'comment_count': int,
  39. 'comments': list,
  40. },
  41. }, {
  42. # missing description
  43. 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
  44. 'info_dict': {
  45. 'id': 'BA-pQFBG8HZ',
  46. 'ext': 'mp4',
  47. 'title': 'Video by britneyspears',
  48. 'thumbnail': r're:^https?://.*\.jpg',
  49. 'duration': 0,
  50. 'timestamp': 1453760977,
  51. 'upload_date': '20160125',
  52. 'uploader_id': 'britneyspears',
  53. 'uploader': 'Britney Spears',
  54. 'like_count': int,
  55. 'comment_count': int,
  56. 'comments': list,
  57. },
  58. 'params': {
  59. 'skip_download': True,
  60. },
  61. }, {
  62. # multi video post
  63. 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
  64. 'playlist': [{
  65. 'info_dict': {
  66. 'id': 'BQ0dSaohpPW',
  67. 'ext': 'mp4',
  68. 'title': 'Video 1',
  69. },
  70. }, {
  71. 'info_dict': {
  72. 'id': 'BQ0dTpOhuHT',
  73. 'ext': 'mp4',
  74. 'title': 'Video 2',
  75. },
  76. }, {
  77. 'info_dict': {
  78. 'id': 'BQ0dT7RBFeF',
  79. 'ext': 'mp4',
  80. 'title': 'Video 3',
  81. },
  82. }],
  83. 'info_dict': {
  84. 'id': 'BQ0eAlwhDrw',
  85. 'title': 'Post by instagram',
  86. 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
  87. },
  88. }, {
  89. # IGTV
  90. 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
  91. 'info_dict': {
  92. 'id': 'BkfuX9UB-eK',
  93. 'ext': 'mp4',
  94. 'title': 'Fingerboarding Tricks with @cass.fb',
  95. 'thumbnail': r're:^https?://.*\.jpg',
  96. 'duration': 53.83,
  97. 'timestamp': 1530032919,
  98. 'upload_date': '20180626',
  99. 'uploader_id': 'instagram',
  100. 'uploader': 'Instagram',
  101. 'like_count': int,
  102. 'comment_count': int,
  103. 'comments': list,
  104. 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
  105. }
  106. }, {
  107. 'url': 'https://instagram.com/p/-Cmh1cukG2/',
  108. 'only_matching': True,
  109. }, {
  110. 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
  111. 'only_matching': True,
  112. }, {
  113. 'url': 'https://www.instagram.com/tv/aye83DjauH/',
  114. 'only_matching': True,
  115. }, {
  116. 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
  117. 'only_matching': True,
  118. }]
  119. @staticmethod
  120. def _extract_embed_url(webpage):
  121. mobj = re.search(
  122. r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
  123. webpage)
  124. if mobj:
  125. return mobj.group('url')
  126. blockquote_el = get_element_by_attribute(
  127. 'class', 'instagram-media', webpage)
  128. if blockquote_el is None:
  129. return
  130. mobj = re.search(
  131. r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
  132. if mobj:
  133. return mobj.group('link')
  134. def _real_extract(self, url):
  135. mobj = re.match(self._VALID_URL, url)
  136. video_id = mobj.group('id')
  137. url = mobj.group('url')
  138. webpage = self._download_webpage(url, video_id)
  139. (media, video_url, description, thumbnail, timestamp, uploader,
  140. uploader_id, like_count, comment_count, comments, height,
  141. width) = [None] * 12
  142. shared_data = self._parse_json(
  143. self._search_regex(
  144. r'window\._sharedData\s*=\s*({.+?});',
  145. webpage, 'shared data', default='{}'),
  146. video_id, fatal=False)
  147. if shared_data:
  148. media = try_get(
  149. shared_data,
  150. (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
  151. lambda x: x['entry_data']['PostPage'][0]['media']),
  152. dict)
  153. # _sharedData.entry_data.PostPage is empty when authenticated (see
  154. # https://github.com/ytdl-org/youtube-dl/pull/22880)
  155. if not media:
  156. additional_data = self._parse_json(
  157. self._search_regex(
  158. r'window\.__additionalDataLoaded\s*\(\s*[^,]+,\s*({.+?})\s*\)\s*;',
  159. webpage, 'additional data', default='{}'),
  160. video_id, fatal=False)
  161. if additional_data:
  162. media = try_get(
  163. additional_data, lambda x: x['graphql']['shortcode_media'],
  164. dict)
  165. if media:
  166. video_url = media.get('video_url')
  167. height = int_or_none(media.get('dimensions', {}).get('height'))
  168. width = int_or_none(media.get('dimensions', {}).get('width'))
  169. description = try_get(
  170. media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
  171. compat_str) or media.get('caption')
  172. title = media.get('title')
  173. thumbnail = media.get('display_src') or media.get('display_url')
  174. duration = float_or_none(media.get('video_duration'))
  175. timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
  176. uploader = media.get('owner', {}).get('full_name')
  177. uploader_id = media.get('owner', {}).get('username')
  178. def get_count(keys, kind):
  179. if not isinstance(keys, (list, tuple)):
  180. keys = [keys]
  181. for key in keys:
  182. count = int_or_none(try_get(
  183. media, (lambda x: x['edge_media_%s' % key]['count'],
  184. lambda x: x['%ss' % kind]['count'])))
  185. if count is not None:
  186. return count
  187. like_count = get_count('preview_like', 'like')
  188. comment_count = get_count(
  189. ('preview_comment', 'to_comment', 'to_parent_comment'), 'comment')
  190. comments = [{
  191. 'author': comment.get('user', {}).get('username'),
  192. 'author_id': comment.get('user', {}).get('id'),
  193. 'id': comment.get('id'),
  194. 'text': comment.get('text'),
  195. 'timestamp': int_or_none(comment.get('created_at')),
  196. } for comment in media.get(
  197. 'comments', {}).get('nodes', []) if comment.get('text')]
  198. if not video_url:
  199. edges = try_get(
  200. media, lambda x: x['edge_sidecar_to_children']['edges'],
  201. list) or []
  202. if edges:
  203. entries = []
  204. for edge_num, edge in enumerate(edges, start=1):
  205. node = try_get(edge, lambda x: x['node'], dict)
  206. if not node:
  207. continue
  208. node_video_url = url_or_none(node.get('video_url'))
  209. if not node_video_url:
  210. continue
  211. entries.append({
  212. 'id': node.get('shortcode') or node['id'],
  213. 'title': node.get('title') or 'Video %d' % edge_num,
  214. 'url': node_video_url,
  215. 'thumbnail': node.get('display_url'),
  216. 'duration': float_or_none(node.get('video_duration')),
  217. 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
  218. 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
  219. 'view_count': int_or_none(node.get('video_view_count')),
  220. })
  221. return self.playlist_result(
  222. entries, video_id,
  223. 'Post by %s' % uploader_id if uploader_id else None,
  224. description)
  225. if not video_url:
  226. video_url = self._og_search_video_url(webpage, secure=False)
  227. formats = [{
  228. 'url': video_url,
  229. 'width': width,
  230. 'height': height,
  231. }]
  232. if not uploader_id:
  233. uploader_id = self._search_regex(
  234. r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
  235. webpage, 'uploader id', fatal=False)
  236. if not description:
  237. description = self._search_regex(
  238. r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
  239. if description is not None:
  240. description = lowercase_escape(description)
  241. if not thumbnail:
  242. thumbnail = self._og_search_thumbnail(webpage)
  243. return {
  244. 'id': video_id,
  245. 'formats': formats,
  246. 'ext': 'mp4',
  247. 'title': title or 'Video by %s' % uploader_id,
  248. 'description': description,
  249. 'duration': duration,
  250. 'thumbnail': thumbnail,
  251. 'timestamp': timestamp,
  252. 'uploader_id': uploader_id,
  253. 'uploader': uploader,
  254. 'like_count': like_count,
  255. 'comment_count': comment_count,
  256. 'comments': comments,
  257. }
  258. class InstagramPlaylistIE(InfoExtractor):
  259. # A superclass for handling any kind of query based on GraphQL which
  260. # results in a playlist.
  261. _gis_tmpl = None # used to cache GIS request type
  262. def _parse_graphql(self, webpage, item_id):
  263. # Reads a webpage and returns its GraphQL data.
  264. return self._parse_json(
  265. self._search_regex(
  266. r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
  267. item_id)
  268. def _extract_graphql(self, data, url):
  269. # Parses GraphQL queries containing videos and generates a playlist.
  270. def get_count(suffix):
  271. return int_or_none(try_get(
  272. node, lambda x: x['edge_media_' + suffix]['count']))
  273. uploader_id = self._match_id(url)
  274. csrf_token = data['config']['csrf_token']
  275. rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
  276. cursor = ''
  277. for page_num in itertools.count(1):
  278. variables = {
  279. 'first': 12,
  280. 'after': cursor,
  281. }
  282. variables.update(self._query_vars_for(data))
  283. variables = json.dumps(variables)
  284. if self._gis_tmpl:
  285. gis_tmpls = [self._gis_tmpl]
  286. else:
  287. gis_tmpls = [
  288. '%s' % rhx_gis,
  289. '',
  290. '%s:%s' % (rhx_gis, csrf_token),
  291. '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent']),
  292. ]
  293. # try all of the ways to generate a GIS query, and not only use the
  294. # first one that works, but cache it for future requests
  295. for gis_tmpl in gis_tmpls:
  296. try:
  297. json_data = self._download_json(
  298. 'https://www.instagram.com/graphql/query/', uploader_id,
  299. 'Downloading JSON page %d' % page_num, headers={
  300. 'X-Requested-With': 'XMLHttpRequest',
  301. 'X-Instagram-GIS': hashlib.md5(
  302. ('%s:%s' % (gis_tmpl, variables)).encode('utf-8')).hexdigest(),
  303. }, query={
  304. 'query_hash': self._QUERY_HASH,
  305. 'variables': variables,
  306. })
  307. media = self._parse_timeline_from(json_data)
  308. self._gis_tmpl = gis_tmpl
  309. break
  310. except ExtractorError as e:
  311. # if it's an error caused by a bad query, and there are
  312. # more GIS templates to try, ignore it and keep trying
  313. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  314. if gis_tmpl != gis_tmpls[-1]:
  315. continue
  316. raise
  317. edges = media.get('edges')
  318. if not edges or not isinstance(edges, list):
  319. break
  320. for edge in edges:
  321. node = edge.get('node')
  322. if not node or not isinstance(node, dict):
  323. continue
  324. if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
  325. continue
  326. video_id = node.get('shortcode')
  327. if not video_id:
  328. continue
  329. info = self.url_result(
  330. 'https://instagram.com/p/%s/' % video_id,
  331. ie=InstagramIE.ie_key(), video_id=video_id)
  332. description = try_get(
  333. node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
  334. compat_str)
  335. thumbnail = node.get('thumbnail_src') or node.get('display_src')
  336. timestamp = int_or_none(node.get('taken_at_timestamp'))
  337. comment_count = get_count('to_comment')
  338. like_count = get_count('preview_like')
  339. view_count = int_or_none(node.get('video_view_count'))
  340. info.update({
  341. 'description': description,
  342. 'thumbnail': thumbnail,
  343. 'timestamp': timestamp,
  344. 'comment_count': comment_count,
  345. 'like_count': like_count,
  346. 'view_count': view_count,
  347. })
  348. yield info
  349. page_info = media.get('page_info')
  350. if not page_info or not isinstance(page_info, dict):
  351. break
  352. has_next_page = page_info.get('has_next_page')
  353. if not has_next_page:
  354. break
  355. cursor = page_info.get('end_cursor')
  356. if not cursor or not isinstance(cursor, compat_str):
  357. break
  358. def _real_extract(self, url):
  359. user_or_tag = self._match_id(url)
  360. webpage = self._download_webpage(url, user_or_tag)
  361. data = self._parse_graphql(webpage, user_or_tag)
  362. self._set_cookie('instagram.com', 'ig_pr', '1')
  363. return self.playlist_result(
  364. self._extract_graphql(data, url), user_or_tag, user_or_tag)
  365. class InstagramUserIE(InstagramPlaylistIE):
  366. _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
  367. IE_DESC = 'Instagram user profile'
  368. IE_NAME = 'instagram:user'
  369. _TEST = {
  370. 'url': 'https://instagram.com/porsche',
  371. 'info_dict': {
  372. 'id': 'porsche',
  373. 'title': 'porsche',
  374. },
  375. 'playlist_count': 5,
  376. 'params': {
  377. 'extract_flat': True,
  378. 'skip_download': True,
  379. 'playlistend': 5,
  380. }
  381. }
  382. _QUERY_HASH = '42323d64886122307be10013ad2dcc44',
  383. @staticmethod
  384. def _parse_timeline_from(data):
  385. # extracts the media timeline data from a GraphQL result
  386. return data['data']['user']['edge_owner_to_timeline_media']
  387. @staticmethod
  388. def _query_vars_for(data):
  389. # returns a dictionary of variables to add to the timeline query based
  390. # on the GraphQL of the original page
  391. return {
  392. 'id': data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
  393. }
  394. class InstagramTagIE(InstagramPlaylistIE):
  395. _VALID_URL = r'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
  396. IE_DESC = 'Instagram hashtag search'
  397. IE_NAME = 'instagram:tag'
  398. _TEST = {
  399. 'url': 'https://instagram.com/explore/tags/lolcats',
  400. 'info_dict': {
  401. 'id': 'lolcats',
  402. 'title': 'lolcats',
  403. },
  404. 'playlist_count': 50,
  405. 'params': {
  406. 'extract_flat': True,
  407. 'skip_download': True,
  408. 'playlistend': 50,
  409. }
  410. }
  411. _QUERY_HASH = 'f92f56d47dc7a55b606908374b43a314',
  412. @staticmethod
  413. def _parse_timeline_from(data):
  414. # extracts the media timeline data from a GraphQL result
  415. return data['data']['hashtag']['edge_hashtag_to_media']
  416. @staticmethod
  417. def _query_vars_for(data):
  418. # returns a dictionary of variables to add to the timeline query based
  419. # on the GraphQL of the original page
  420. return {
  421. 'tag_name':
  422. data['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
  423. }