9 from .common
import InfoExtractor
10 from ..compat
import (
17 get_element_by_attribute
,
28 class InstagramBaseIE(InfoExtractor
):
29 _NETRC_MACHINE
= 'instagram'
32 def _perform_login(self
, username
, password
):
33 if self
._IS
_LOGGED
_IN
:
36 login_webpage
= self
._download
_webpage
(
37 'https://www.instagram.com/accounts/login/', None,
38 note
='Downloading login webpage', errnote
='Failed to download login webpage')
40 shared_data
= self
._parse
_json
(
42 r
'window\._sharedData\s*=\s*({.+?});',
43 login_webpage
, 'shared data', default
='{}'),
46 login
= self
._download
_json
('https://www.instagram.com/accounts/login/ajax/', None, note
='Logging in', headers
={
48 'X-IG-App-ID': '936619743392459',
49 'X-ASBD-ID': '198387',
50 'X-IG-WWW-Claim': '0',
51 'X-Requested-With': 'XMLHttpRequest',
52 'X-CSRFToken': shared_data
['config']['csrf_token'],
53 'X-Instagram-AJAX': shared_data
['rollout_hash'],
54 'Referer': 'https://www.instagram.com/',
55 }, data
=urlencode_postdata({
56 'enc_password': f
'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
59 'optIntoOneTap': 'false',
60 'stopDeletionNonce': '',
61 'trustedDeviceRecords': '{}',
64 if not login
.get('authenticated'):
65 if login
.get('message'):
66 raise ExtractorError(f
'Unable to login: {login["message"]}')
67 elif login
.get('user'):
68 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected
=True)
69 elif login
.get('user') is False:
70 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected
=True)
71 raise ExtractorError('Unable to login')
72 InstagramBaseIE
._IS
_LOGGED
_IN
= True
74 def _get_count(self
, media
, kind
, *keys
):
76 media
, (kind
, 'count'), *((f
'edge_media_{key}', 'count') for key
in keys
),
77 expected_type
=int_or_none
)
79 def _get_dimension(self
, name
, media
, webpage
=None):
81 traverse_obj(media
, ('dimensions', name
), expected_type
=int_or_none
)
82 or int_or_none(self
._html
_search
_meta
(
83 (f
'og:video:{name}', f
'video:{name}'), webpage
or '', default
=None)))
85 def _extract_nodes(self
, nodes
, is_direct
=False):
86 for idx
, node
in enumerate(nodes
, start
=1):
87 if node
.get('__typename') != 'GraphVideo' and node
.get('is_video') is not True:
90 video_id
= node
.get('shortcode')
94 'id': video_id
or node
['id'],
95 'url': node
.get('video_url'),
96 'width': self
._get
_dimension
('width', node
),
97 'height': self
._get
_dimension
('height', node
),
99 'Referer': 'https://www.instagram.com/',
107 'ie_key': 'Instagram',
109 'url': f
'https://instagram.com/p/{video_id}',
114 'title': node
.get('title') or (f
'Video {idx}' if is_direct
else None),
115 'description': traverse_obj(
116 node
, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type
=str),
117 'thumbnail': traverse_obj(
118 node
, 'display_url', 'thumbnail_src', 'display_src', expected_type
=url_or_none
),
119 'duration': float_or_none(node
.get('video_duration')),
120 'timestamp': int_or_none(node
.get('taken_at_timestamp')),
121 'view_count': int_or_none(node
.get('video_view_count')),
122 'comment_count': self
._get
_count
(node
, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
123 'like_count': self
._get
_count
(node
, 'likes', 'preview_like'),
126 def _extract_product_media(self
, product_media
):
127 media_id
= product_media
.get('code') or product_media
.get('id')
128 vcodec
= product_media
.get('video_codec')
129 dash_manifest_raw
= product_media
.get('video_dash_manifest')
130 videos_list
= product_media
.get('video_versions')
131 if not (dash_manifest_raw
or videos_list
):
135 'format_id': format
.get('id'),
136 'url': format
.get('url'),
137 'width': format
.get('width'),
138 'height': format
.get('height'),
140 } for format
in videos_list
or []]
141 if dash_manifest_raw
:
142 formats
.extend(self
._parse
_mpd
_formats
(self
._parse
_xml
(dash_manifest_raw
, media_id
), mpd_id
='dash'))
143 self
._sort
_formats
(formats
)
146 'url': thumbnail
.get('url'),
147 'width': thumbnail
.get('width'),
148 'height': thumbnail
.get('height')
149 } for thumbnail
in traverse_obj(product_media
, ('image_versions2', 'candidates')) or []]
152 'duration': float_or_none(product_media
.get('video_duration')),
154 'thumbnails': thumbnails
157 def _extract_product(self
, product_info
):
158 if isinstance(product_info
, list):
159 product_info
= product_info
[0]
161 user_info
= product_info
.get('user') or {}
163 'id': product_info
.get('code') or product_info
.get('id'),
164 'title': product_info
.get('title') or f
'Video by {user_info.get("username")}',
165 'description': traverse_obj(product_info
, ('caption', 'text'), expected_type
=str_or_none
),
166 'timestamp': int_or_none(product_info
.get('taken_at')),
167 'channel': user_info
.get('username'),
168 'uploader': user_info
.get('full_name'),
169 'uploader_id': str_or_none(user_info
.get('pk')),
170 'view_count': int_or_none(product_info
.get('view_count')),
171 'like_count': int_or_none(product_info
.get('like_count')),
172 'comment_count': int_or_none(product_info
.get('comment_count')),
174 'Referer': 'https://www.instagram.com/',
177 carousel_media
= product_info
.get('carousel_media')
182 'title': f
'Post by {user_info.get("username")}',
185 **self
._extract
_product
_media
(product_media
),
186 } for product_media
in carousel_media
],
191 **self
._extract
_product
_media
(product_info
)
195 class InstagramIOSIE(InfoExtractor
):
196 IE_DESC
= 'IOS instagram:// URL'
197 _VALID_URL
= r
'instagram://media\?id=(?P<id>[\d_]+)'
199 'url': 'instagram://media?id=482584233761418119',
200 'md5': '0d2da106a9d2631273e192b372806516',
204 'title': 'Video by naomipq',
205 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
206 'thumbnail': r
're:^https?://.*\.jpg',
208 'timestamp': 1371748545,
209 'upload_date': '20130620',
210 'uploader_id': 'naomipq',
211 'uploader': 'B E A U T Y F O R A S H E S',
213 'comment_count': int,
216 'add_ie': ['Instagram']
219 def _get_id(self
, id):
220 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
221 chrs
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
222 media_id
= int(id.split('_')[0])
226 media_id
= (media_id
- r
) // 64
227 shortened_id
= chrs
[r
] + shortened_id
230 def _real_extract(self
, url
):
232 '_type': 'url_transparent',
233 'url': f
'http://instagram.com/tv/{self._get_id(self._match_id(url))}/',
234 'ie_key': 'Instagram',
238 class InstagramIE(InstagramBaseIE
):
239 _VALID_URL
= r
'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
241 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
242 'md5': '0d2da106a9d2631273e192b372806516',
246 'title': 'Video by naomipq',
247 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
248 'thumbnail': r
're:^https?://.*\.jpg',
250 'timestamp': 1371748545,
251 'upload_date': '20130620',
252 'uploader_id': '2815873',
253 'uploader': 'B E A U T Y F O R A S H E S',
254 'channel': 'naomipq',
256 'comment_count': int,
260 # missing description
261 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
265 'title': 'Video by britneyspears',
266 'thumbnail': r
're:^https?://.*\.jpg',
268 'timestamp': 1453760977,
269 'upload_date': '20160125',
270 'uploader_id': '12246775',
271 'uploader': 'Britney Spears',
272 'channel': 'britneyspears',
274 'comment_count': int,
278 'skip_download': True,
282 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
304 'title': 'Post by instagram',
305 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
309 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
313 'title': 'Fingerboarding Tricks with @cass.fb',
314 'thumbnail': r
're:^https?://.*\.jpg',
316 'timestamp': 1530032919,
317 'upload_date': '20180626',
318 'uploader_id': '25025320',
319 'uploader': 'Instagram',
320 'channel': 'instagram',
322 'comment_count': int,
324 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
327 'url': 'https://instagram.com/p/-Cmh1cukG2/',
328 'only_matching': True,
330 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
331 'only_matching': True,
333 'url': 'https://www.instagram.com/tv/aye83DjauH/',
334 'only_matching': True,
336 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
337 'only_matching': True,
339 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
340 'only_matching': True,
344 def _extract_embed_url(webpage
):
346 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//(?
:www\
.)?instagram\
.com
/p
/[^
/]+/embed
.*?
)\
1',
349 return mobj.group('url
')
351 blockquote_el = get_element_by_attribute(
352 'class', 'instagram
-media
', webpage)
353 if blockquote_el is None:
357 r'<a
[^
>]+href
=([\'"])(?P<link>[^\'"]+)\
1', blockquote_el)
359 return mobj.group('link
')
361 def _real_extract(self, url):
362 video_id, url = self._match_valid_url(url).group('id', 'url
')
363 webpage, urlh = self._download_webpage_handle(url, video_id)
364 if 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
365 self.report_warning('Main webpage
is locked behind the login page
. '
366 'Retrying
with embed
webpage (Note that some metadata might be missing
)')
367 webpage = self._download_webpage(
368 'https
://www
.instagram
.com
/p
/%s/embed
/' % video_id, video_id, note='Downloading embed webpage
')
370 shared_data = self._parse_json(
372 r'window\
._sharedData\s
*=\s
*({.+?}
);',
373 webpage, 'shared data
', default='{}'),
374 video_id, fatal=False)
375 media = traverse_obj(
377 ('entry_data
', 'PostPage
', 0, 'graphql
', 'shortcode_media
'),
378 ('entry_data
', 'PostPage
', 0, 'media
'),
381 # _sharedData.entry_data.PostPage is empty when authenticated (see
382 # https://github.com/ytdl-org/youtube-dl/pull/22880)
384 additional_data = self._parse_json(
386 r'window\
.__additionalDataLoaded\s
*\
(\s
*[^
,]+,\s
*({.+?}
)\s
*\
);',
387 webpage, 'additional data
', default='{}'),
388 video_id, fatal=False)
389 product_item = traverse_obj(additional_data, ('items
', 0), expected_type=dict)
391 return self._extract_product(product_item)
392 media = traverse_obj(additional_data, ('graphql
', 'shortcode_media
'), 'shortcode_media
', expected_type=dict) or {}
394 if not media and 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
395 self.raise_login_required('You need to log
in to access this content
')
397 username = traverse_obj(media, ('owner
', 'username
')) or self._search_regex(
398 r'"owner"\s
*:\s
*{\s
*"username"\s
*:\s
*"(.+?)"', webpage, 'username
', fatal=False)
401 traverse_obj(media, ('edge_media_to_caption
', 'edges
', 0, 'node
', 'text
'), expected_type=str)
402 or media.get('caption
'))
404 description = self._search_regex(
405 r'"caption"\s
*:\s
*"(.+?)"', webpage, 'description
', default=None)
406 if description is not None:
407 description = lowercase_escape(description)
409 video_url = media.get('video_url
')
411 nodes = traverse_obj(media, ('edge_sidecar_to_children
', 'edges
', ..., 'node
'), expected_type=dict) or []
413 return self.playlist_result(
414 self._extract_nodes(nodes, True), video_id,
415 format_field(username, template='Post by
%s'), description)
417 video_url = self._og_search_video_url(webpage, secure=False)
421 'width
': self._get_dimension('width
', media, webpage),
422 'height
': self._get_dimension('height
', media, webpage),
424 dash = traverse_obj(media, ('dash_info
', 'video_dash_manifest
'))
426 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash
'))
427 self._sort_formats(formats)
429 comment_data = traverse_obj(media, ('edge_media_to_parent_comment
', 'edges
'))
431 'author
': traverse_obj(comment_dict, ('node
', 'owner
', 'username
')),
432 'author_id
': traverse_obj(comment_dict, ('node
', 'owner
', 'id')),
433 'id': traverse_obj(comment_dict, ('node
', 'id')),
434 'text
': traverse_obj(comment_dict, ('node
', 'text
')),
435 'timestamp
': traverse_obj(comment_dict, ('node
', 'created_at
'), expected_type=int_or_none),
436 } for comment_dict in comment_data] if comment_data else None
438 display_resources = (
439 media.get('display_resources
')
440 or [{'src': media.get(key)} for key in ('display_src
', 'display_url
')]
441 or [{'src': self._og_search_thumbnail(webpage)}])
443 'url
': thumbnail['src
'],
444 'width
': thumbnail.get('config_width
'),
445 'height
': thumbnail.get('config_height
'),
446 } for thumbnail in display_resources if thumbnail.get('src
')]
451 'title
': media.get('title
') or 'Video by
%s' % username,
452 'description
': description,
453 'duration
': float_or_none(media.get('video_duration
')),
454 'timestamp
': traverse_obj(media, 'taken_at_timestamp
', 'date
', expected_type=int_or_none),
455 'uploader_id
': traverse_obj(media, ('owner
', 'id')),
456 'uploader
': traverse_obj(media, ('owner
', 'full_name
')),
458 'like_count
': self._get_count(media, 'likes
', 'preview_like
') or str_to_int(self._search_regex(
459 r'data
-log
-event
="likeCountClick"[^
>]*>[^\d
]*([\d
,\
.]+)', webpage, 'like count
', fatal=False)),
460 'comment_count
': self._get_count(media, 'comments
', 'preview_comment
', 'to_comment
', 'to_parent_comment
'),
461 'comments
': comments,
462 'thumbnails
': thumbnails,
464 'Referer
': 'https
://www
.instagram
.com
/',
469 class InstagramPlaylistBaseIE(InstagramBaseIE):
470 _gis_tmpl = None # used to cache GIS request type
472 def _parse_graphql(self, webpage, item_id):
473 # Reads a webpage and returns its GraphQL data.
474 return self._parse_json(
476 r'sharedData\s
*=\s
*({.+?}
)\s
*;\s
*[<\n]', webpage, 'data
'),
479 def _extract_graphql(self, data, url):
480 # Parses GraphQL queries containing videos and generates a playlist.
481 uploader_id = self._match_id(url)
482 csrf_token = data['config
']['csrf_token
']
483 rhx_gis = data.get('rhx_gis
') or '3c7ca9dcefcf966d11dacf1f151335e8
'
486 for page_num in itertools.count(1):
491 variables.update(self._query_vars_for(data))
492 variables = json.dumps(variables)
495 gis_tmpls = [self._gis_tmpl]
500 '%s:%s' % (rhx_gis, csrf_token),
501 '%s:%s:%s' % (rhx_gis, csrf_token, self.get_param('http_headers
')['User
-Agent
']),
504 # try all of the ways to generate a GIS query, and not only use the
505 # first one that works, but cache it for future requests
506 for gis_tmpl in gis_tmpls:
508 json_data = self._download_json(
509 'https
://www
.instagram
.com
/graphql
/query
/', uploader_id,
510 'Downloading JSON page
%d' % page_num, headers={
511 'X
-Requested
-With
': 'XMLHttpRequest
',
512 'X
-Instagram
-GIS
': hashlib.md5(
513 ('%s:%s' % (gis_tmpl, variables)).encode('utf
-8')).hexdigest(),
515 'query_hash
': self._QUERY_HASH,
516 'variables
': variables,
518 media = self._parse_timeline_from(json_data)
519 self._gis_tmpl = gis_tmpl
521 except ExtractorError as e:
522 # if it's an error caused by a bad query
, and there are
523 # more GIS templates to try, ignore it and keep trying
524 if isinstance(e
.cause
, compat_HTTPError
) and e
.cause
.code
== 403:
525 if gis_tmpl
!= gis_tmpls
[-1]:
529 nodes
= traverse_obj(media
, ('edges', ..., 'node'), expected_type
=dict) or []
532 yield from self
._extract
_nodes
(nodes
)
534 has_next_page
= traverse_obj(media
, ('page_info', 'has_next_page'))
535 cursor
= traverse_obj(media
, ('page_info', 'end_cursor'), expected_type
=str)
536 if not has_next_page
or not cursor
:
539 def _real_extract(self
, url
):
540 user_or_tag
= self
._match
_id
(url
)
541 webpage
= self
._download
_webpage
(url
, user_or_tag
)
542 data
= self
._parse
_graphql
(webpage
, user_or_tag
)
544 self
._set
_cookie
('instagram.com', 'ig_pr', '1')
546 return self
.playlist_result(
547 self
._extract
_graphql
(data
, url
), user_or_tag
, user_or_tag
)
550 class InstagramUserIE(InstagramPlaylistBaseIE
):
551 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
552 IE_DESC
= 'Instagram user profile'
553 IE_NAME
= 'instagram:user'
555 'url': 'https://instagram.com/porsche',
562 'extract_flat': True,
563 'skip_download': True,
568 _QUERY_HASH
= '42323d64886122307be10013ad2dcc44',
571 def _parse_timeline_from(data
):
572 # extracts the media timeline data from a GraphQL result
573 return data
['data']['user']['edge_owner_to_timeline_media']
576 def _query_vars_for(data
):
577 # returns a dictionary of variables to add to the timeline query based
578 # on the GraphQL of the original page
580 'id': data
['entry_data']['ProfilePage'][0]['graphql']['user']['id']
584 class InstagramTagIE(InstagramPlaylistBaseIE
):
585 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
586 IE_DESC
= 'Instagram hashtag search URLs'
587 IE_NAME
= 'instagram:tag'
589 'url': 'https://instagram.com/explore/tags/lolcats',
594 'playlist_count': 50,
596 'extract_flat': True,
597 'skip_download': True,
602 _QUERY_HASH
= 'f92f56d47dc7a55b606908374b43a314',
605 def _parse_timeline_from(data
):
606 # extracts the media timeline data from a GraphQL result
607 return data
['data']['hashtag']['edge_hashtag_to_media']
610 def _query_vars_for(data
):
611 # returns a dictionary of variables to add to the timeline query based
612 # on the GraphQL of the original page
615 data
['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
619 class InstagramStoryIE(InstagramBaseIE
):
620 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
621 IE_NAME
= 'instagram:story'
624 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
626 'id': '18090946048123978',
629 'playlist_mincount': 50
632 def _real_extract(self
, url
):
633 username
, story_id
= self
._match
_valid
_url
(url
).groups()
635 story_info_url
= f
'{username}/{story_id}/?__a=1' if username
== 'highlights' else f
'{username}/?__a=1'
636 story_info
= self
._download
_json
(f
'https://www.instagram.com/stories/{story_info_url}', story_id
, headers
={
637 'X-IG-App-ID': 936619743392459,
640 'X-Requested-With': 'XMLHttpRequest',
643 user_id
= story_info
['user']['id']
644 highlight_title
= traverse_obj(story_info
, ('highlight', 'title'))
646 story_info_url
= user_id
if username
!= 'highlights' else f
'highlight:{story_id}'
647 videos
= self
._download
_json
(f
'https://i.instagram.com/api/v1/feed/reels_media/?reel_ids={story_info_url}', story_id
, headers
={
648 'X-IG-App-ID': 936619743392459,
653 full_name
= traverse_obj(videos
, ('user', 'full_name'))
656 if not (username
and username
!= 'highlights' and full_name
):
657 user_info
= self
._download
_json
(
658 f
'https://i.instagram.com/api/v1/users/{user_id}/info/', story_id
, headers
={
659 'User-Agent': 'Mozilla/5.0 (Linux; Android 11; SM-A505F Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/96.0.4664.45 Mobile Safari/537.36 Instagram 214.1.0.29.120 Android (30/11; 450dpi; 1080x2122; samsung; SM-A505F; a50; exynos9610; en_US; 333717274)',
660 }, note
='Downloading user info')
662 username
= traverse_obj(user_info
, ('user', 'username')) or username
663 full_name
= traverse_obj(user_info
, ('user', 'full_name')) or full_name
665 highlights
= traverse_obj(videos
, (f
'highlight:{story_id}', 'items'), (str(user_id
), 'items'))
666 return self
.playlist_result([{
667 **self
._extract
_product
(highlight
),
668 'title': f
'Story by {username}',
669 'uploader': full_name
,
670 'uploader_id': user_id
,
671 } for highlight
in highlights
], playlist_id
=story_id
, playlist_title
=highlight_title
)