[ie/dropbox] Fix password-protected video extraction (#11636)
[yt-dlp3.git] / yt_dlp / extractor / instagram.py
blobdee8cb85d5293b82da5dbac4512b074cafc14fc7
1 import hashlib
2 import itertools
3 import json
4 import re
5 import time
7 from .common import InfoExtractor
8 from ..networking.exceptions import HTTPError
9 from ..utils import (
10 ExtractorError,
11 decode_base_n,
12 encode_base_n,
13 filter_dict,
14 float_or_none,
15 format_field,
16 get_element_by_attribute,
17 int_or_none,
18 lowercase_escape,
19 str_or_none,
20 str_to_int,
21 traverse_obj,
22 url_or_none,
23 urlencode_postdata,
26 _ENCODING_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
29 def _pk_to_id(media_id):
30 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
31 return encode_base_n(int(media_id.split('_')[0]), table=_ENCODING_CHARS)
34 def _id_to_pk(shortcode):
35 """Covert a shortcode to a numeric value"""
36 return decode_base_n(shortcode[:11], table=_ENCODING_CHARS)
39 class InstagramBaseIE(InfoExtractor):
40 _NETRC_MACHINE = 'instagram'
41 _IS_LOGGED_IN = False
43 _API_BASE_URL = 'https://i.instagram.com/api/v1'
44 _LOGIN_URL = 'https://www.instagram.com/accounts/login'
45 _API_HEADERS = {
46 'X-IG-App-ID': '936619743392459',
47 'X-ASBD-ID': '198387',
48 'X-IG-WWW-Claim': '0',
49 'Origin': 'https://www.instagram.com',
50 'Accept': '*/*',
53 def _perform_login(self, username, password):
54 if self._IS_LOGGED_IN:
55 return
57 login_webpage = self._download_webpage(
58 self._LOGIN_URL, None, note='Downloading login webpage', errnote='Failed to download login webpage')
60 shared_data = self._parse_json(self._search_regex(
61 r'window\._sharedData\s*=\s*({.+?});', login_webpage, 'shared data', default='{}'), None)
63 login = self._download_json(
64 f'{self._LOGIN_URL}/ajax/', None, note='Logging in', headers={
65 **self._API_HEADERS,
66 'X-Requested-With': 'XMLHttpRequest',
67 'X-CSRFToken': shared_data['config']['csrf_token'],
68 'X-Instagram-AJAX': shared_data['rollout_hash'],
69 'Referer': 'https://www.instagram.com/',
70 }, data=urlencode_postdata({
71 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
72 'username': username,
73 'queryParams': '{}',
74 'optIntoOneTap': 'false',
75 'stopDeletionNonce': '',
76 'trustedDeviceRecords': '{}',
77 }))
79 if not login.get('authenticated'):
80 if login.get('message'):
81 raise ExtractorError(f'Unable to login: {login["message"]}')
82 elif login.get('user'):
83 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected=True)
84 elif login.get('user') is False:
85 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected=True)
86 raise ExtractorError('Unable to login')
87 InstagramBaseIE._IS_LOGGED_IN = True
89 def _get_count(self, media, kind, *keys):
90 return traverse_obj(
91 media, (kind, 'count'), *((f'edge_media_{key}', 'count') for key in keys),
92 expected_type=int_or_none)
94 def _get_dimension(self, name, media, webpage=None):
95 return (
96 traverse_obj(media, ('dimensions', name), expected_type=int_or_none)
97 or int_or_none(self._html_search_meta(
98 (f'og:video:{name}', f'video:{name}'), webpage or '', default=None)))
100 def _extract_nodes(self, nodes, is_direct=False):
101 for idx, node in enumerate(nodes, start=1):
102 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
103 continue
105 video_id = node.get('shortcode')
107 if is_direct:
108 info = {
109 'id': video_id or node['id'],
110 'url': node.get('video_url'),
111 'width': self._get_dimension('width', node),
112 'height': self._get_dimension('height', node),
113 'http_headers': {
114 'Referer': 'https://www.instagram.com/',
117 elif not video_id:
118 continue
119 else:
120 info = {
121 '_type': 'url',
122 'ie_key': 'Instagram',
123 'id': video_id,
124 'url': f'https://instagram.com/p/{video_id}',
127 yield {
128 **info,
129 'title': node.get('title') or (f'Video {idx}' if is_direct else None),
130 'description': traverse_obj(
131 node, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type=str),
132 'thumbnail': traverse_obj(
133 node, 'display_url', 'thumbnail_src', 'display_src', expected_type=url_or_none),
134 'duration': float_or_none(node.get('video_duration')),
135 'timestamp': int_or_none(node.get('taken_at_timestamp')),
136 'view_count': int_or_none(node.get('video_view_count')),
137 'comment_count': self._get_count(node, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
138 'like_count': self._get_count(node, 'likes', 'preview_like'),
141 def _extract_product_media(self, product_media):
142 media_id = product_media.get('code') or _pk_to_id(product_media.get('pk'))
143 vcodec = product_media.get('video_codec')
144 dash_manifest_raw = product_media.get('video_dash_manifest')
145 videos_list = product_media.get('video_versions')
146 if not (dash_manifest_raw or videos_list):
147 return {}
149 formats = [{
150 'format_id': fmt.get('id'),
151 'url': fmt.get('url'),
152 'width': fmt.get('width'),
153 'height': fmt.get('height'),
154 'vcodec': vcodec,
155 } for fmt in videos_list or []]
156 if dash_manifest_raw:
157 formats.extend(self._parse_mpd_formats(self._parse_xml(dash_manifest_raw, media_id), mpd_id='dash'))
159 thumbnails = [{
160 'url': thumbnail.get('url'),
161 'width': thumbnail.get('width'),
162 'height': thumbnail.get('height'),
163 } for thumbnail in traverse_obj(product_media, ('image_versions2', 'candidates')) or []]
164 return {
165 'id': media_id,
166 'duration': float_or_none(product_media.get('video_duration')),
167 'formats': formats,
168 'thumbnails': thumbnails,
171 def _extract_product(self, product_info):
172 if isinstance(product_info, list):
173 product_info = product_info[0]
175 user_info = product_info.get('user') or {}
176 info_dict = {
177 'id': _pk_to_id(traverse_obj(product_info, 'pk', 'id', expected_type=str_or_none)[:19]),
178 'title': product_info.get('title') or f'Video by {user_info.get("username")}',
179 'description': traverse_obj(product_info, ('caption', 'text'), expected_type=str_or_none),
180 'timestamp': int_or_none(product_info.get('taken_at')),
181 'channel': user_info.get('username'),
182 'uploader': user_info.get('full_name'),
183 'uploader_id': str_or_none(user_info.get('pk')),
184 'view_count': int_or_none(product_info.get('view_count')),
185 'like_count': int_or_none(product_info.get('like_count')),
186 'comment_count': int_or_none(product_info.get('comment_count')),
187 '__post_extractor': self.extract_comments(_pk_to_id(product_info.get('pk'))),
188 'http_headers': {
189 'Referer': 'https://www.instagram.com/',
192 carousel_media = product_info.get('carousel_media')
193 if carousel_media:
194 return {
195 '_type': 'playlist',
196 **info_dict,
197 'title': f'Post by {user_info.get("username")}',
198 'entries': [{
199 **info_dict,
200 **self._extract_product_media(product_media),
201 } for product_media in carousel_media],
204 return {
205 **info_dict,
206 **self._extract_product_media(product_info),
209 def _get_comments(self, video_id):
210 comments_info = self._download_json(
211 f'{self._API_BASE_URL}/media/{_id_to_pk(video_id)}/comments/?can_support_threading=true&permalink_enabled=false', video_id,
212 fatal=False, errnote='Comments extraction failed', note='Downloading comments info', headers=self._API_HEADERS) or {}
214 comment_data = traverse_obj(comments_info, ('edge_media_to_parent_comment', 'edges'), 'comments')
215 for comment_dict in comment_data or []:
216 yield {
217 'author': traverse_obj(comment_dict, ('node', 'owner', 'username'), ('user', 'username')),
218 'author_id': traverse_obj(comment_dict, ('node', 'owner', 'id'), ('user', 'pk')),
219 'author_thumbnail': traverse_obj(comment_dict, ('node', 'owner', 'profile_pic_url'), ('user', 'profile_pic_url'), expected_type=url_or_none),
220 'id': traverse_obj(comment_dict, ('node', 'id'), 'pk'),
221 'text': traverse_obj(comment_dict, ('node', 'text'), 'text'),
222 'like_count': traverse_obj(comment_dict, ('node', 'edge_liked_by', 'count'), 'comment_like_count', expected_type=int_or_none),
223 'timestamp': traverse_obj(comment_dict, ('node', 'created_at'), 'created_at', expected_type=int_or_none),
227 class InstagramIOSIE(InfoExtractor):
228 IE_DESC = 'IOS instagram:// URL'
229 _VALID_URL = r'instagram://media\?id=(?P<id>[\d_]+)'
230 _TESTS = [{
231 'url': 'instagram://media?id=482584233761418119',
232 'md5': '0d2da106a9d2631273e192b372806516',
233 'info_dict': {
234 'id': 'aye83DjauH',
235 'ext': 'mp4',
236 'title': 'Video by naomipq',
237 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
238 'thumbnail': r're:^https?://.*\.jpg',
239 'duration': 0,
240 'timestamp': 1371748545,
241 'upload_date': '20130620',
242 'uploader_id': 'naomipq',
243 'uploader': 'B E A U T Y F O R A S H E S',
244 'like_count': int,
245 'comment_count': int,
246 'comments': list,
248 'add_ie': ['Instagram'],
251 def _real_extract(self, url):
252 video_id = _pk_to_id(self._match_id(url))
253 return self.url_result(f'http://instagram.com/tv/{video_id}', InstagramIE, video_id)
256 class InstagramIE(InstagramBaseIE):
257 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reels?(?!/audio/))/(?P<id>[^/?#&]+))'
258 _EMBED_REGEX = [r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1']
259 _TESTS = [{
260 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
261 'md5': '0d2da106a9d2631273e192b372806516',
262 'info_dict': {
263 'id': 'aye83DjauH',
264 'ext': 'mp4',
265 'title': 'Video by naomipq',
266 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
267 'thumbnail': r're:^https?://.*\.jpg',
268 'duration': 8.747,
269 'timestamp': 1371748545,
270 'upload_date': '20130620',
271 'uploader_id': '2815873',
272 'uploader': 'B E A U T Y F O R A S H E S',
273 'channel': 'naomipq',
274 'like_count': int,
275 'comment_count': int,
276 'comments': list,
278 'expected_warnings': [
279 'General metadata extraction failed',
280 'Main webpage is locked behind the login page',
282 }, {
283 # reel
284 'url': 'https://www.instagram.com/reel/Chunk8-jurw/',
285 'md5': 'f6d8277f74515fa3ff9f5791426e42b1',
286 'info_dict': {
287 'id': 'Chunk8-jurw',
288 'ext': 'mp4',
289 'title': 'Video by instagram',
290 'description': 'md5:c9cde483606ed6f80fbe9283a6a2b290',
291 'thumbnail': r're:^https?://.*\.jpg',
292 'duration': 5.016,
293 'timestamp': 1661529231,
294 'upload_date': '20220826',
295 'uploader_id': '25025320',
296 'uploader': 'Instagram',
297 'channel': 'instagram',
298 'like_count': int,
299 'comment_count': int,
300 'comments': list,
302 'expected_warnings': [
303 'General metadata extraction failed',
304 'Main webpage is locked behind the login page',
306 }, {
307 # multi video post
308 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
309 'playlist': [{
310 'info_dict': {
311 'id': 'BQ0dSaohpPW',
312 'ext': 'mp4',
313 'title': 'Video 1',
314 'thumbnail': r're:^https?://.*\.jpg',
315 'view_count': int,
317 }, {
318 'info_dict': {
319 'id': 'BQ0dTpOhuHT',
320 'ext': 'mp4',
321 'title': 'Video 2',
322 'thumbnail': r're:^https?://.*\.jpg',
323 'view_count': int,
325 }, {
326 'info_dict': {
327 'id': 'BQ0dT7RBFeF',
328 'ext': 'mp4',
329 'title': 'Video 3',
330 'thumbnail': r're:^https?://.*\.jpg',
331 'view_count': int,
334 'info_dict': {
335 'id': 'BQ0eAlwhDrw',
336 'title': 'Post by instagram',
337 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
339 'expected_warnings': [
340 'General metadata extraction failed',
341 'Main webpage is locked behind the login page',
343 }, {
344 # IGTV
345 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
346 'info_dict': {
347 'id': 'BkfuX9UB-eK',
348 'ext': 'mp4',
349 'title': 'Fingerboarding Tricks with @cass.fb',
350 'thumbnail': r're:^https?://.*\.jpg',
351 'duration': 53.83,
352 'timestamp': 1530032919,
353 'upload_date': '20180626',
354 'uploader_id': '25025320',
355 'uploader': 'Instagram',
356 'channel': 'instagram',
357 'like_count': int,
358 'comment_count': int,
359 'comments': list,
360 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
362 'expected_warnings': [
363 'General metadata extraction failed',
364 'Main webpage is locked behind the login page',
366 }, {
367 'url': 'https://instagram.com/p/-Cmh1cukG2/',
368 'only_matching': True,
369 }, {
370 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
371 'only_matching': True,
372 }, {
373 'url': 'https://www.instagram.com/tv/aye83DjauH/',
374 'only_matching': True,
375 }, {
376 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
377 'only_matching': True,
378 }, {
379 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
380 'only_matching': True,
381 }, {
382 'url': 'https://www.instagram.com/reels/Cop84x6u7CP/',
383 'only_matching': True,
386 @classmethod
387 def _extract_embed_urls(cls, url, webpage):
388 res = tuple(super()._extract_embed_urls(url, webpage))
389 if res:
390 return res
392 mobj = re.search(r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1',
393 get_element_by_attribute('class', 'instagram-media', webpage) or '')
394 if mobj:
395 return [mobj.group('link')]
397 def _real_extract(self, url):
398 video_id, url = self._match_valid_url(url).group('id', 'url')
399 media, webpage = {}, ''
401 if self._get_cookies(url).get('sessionid'):
402 info = traverse_obj(self._download_json(
403 f'{self._API_BASE_URL}/media/{_id_to_pk(video_id)}/info/', video_id,
404 fatal=False, errnote='Video info extraction failed',
405 note='Downloading video info', headers=self._API_HEADERS), ('items', 0))
406 if info:
407 media.update(info)
408 return self._extract_product(media)
410 api_check = self._download_json(
411 f'{self._API_BASE_URL}/web/get_ruling_for_content/?content_type=MEDIA&target_id={_id_to_pk(video_id)}',
412 video_id, headers=self._API_HEADERS, fatal=False, note='Setting up session', errnote=False) or {}
413 csrf_token = self._get_cookies('https://www.instagram.com').get('csrftoken')
415 if not csrf_token:
416 self.report_warning('No csrf token set by Instagram API', video_id)
417 else:
418 csrf_token = csrf_token.value if api_check.get('status') == 'ok' else None
419 if not csrf_token:
420 self.report_warning('Instagram API is not granting access', video_id)
422 variables = {
423 'shortcode': video_id,
424 'child_comment_count': 3,
425 'fetch_comment_count': 40,
426 'parent_comment_count': 24,
427 'has_threaded_comments': True,
429 general_info = self._download_json(
430 'https://www.instagram.com/graphql/query/', video_id, fatal=False, errnote=False,
431 headers={
432 **self._API_HEADERS,
433 'X-CSRFToken': csrf_token or '',
434 'X-Requested-With': 'XMLHttpRequest',
435 'Referer': url,
436 }, query={
437 'doc_id': '8845758582119845',
438 'variables': json.dumps(variables, separators=(',', ':')),
440 media.update(traverse_obj(general_info, ('data', 'xdt_shortcode_media')) or {})
442 if not general_info:
443 self.report_warning('General metadata extraction failed (some metadata might be missing).', video_id)
444 webpage, urlh = self._download_webpage_handle(url, video_id)
445 shared_data = self._search_json(
446 r'window\._sharedData\s*=', webpage, 'shared data', video_id, fatal=False) or {}
448 if shared_data and self._LOGIN_URL not in urlh.url:
449 media.update(traverse_obj(
450 shared_data, ('entry_data', 'PostPage', 0, 'graphql', 'shortcode_media'),
451 ('entry_data', 'PostPage', 0, 'media'), expected_type=dict) or {})
452 else:
453 self.report_warning('Main webpage is locked behind the login page. Retrying with embed webpage (some metadata might be missing).')
454 webpage = self._download_webpage(
455 f'{url}/embed/', video_id, note='Downloading embed webpage', fatal=False) or ''
456 additional_data = self._search_json(
457 r'window\.__additionalDataLoaded\s*\(\s*[^,]+,', webpage, 'additional data', video_id, fatal=False)
458 if not additional_data and not media:
459 self.raise_login_required('Requested content is not available, rate-limit reached or login required')
461 product_item = traverse_obj(additional_data, ('items', 0), expected_type=dict)
462 if product_item:
463 media.update(product_item)
464 return self._extract_product(media)
466 media.update(traverse_obj(
467 additional_data, ('graphql', 'shortcode_media'), 'shortcode_media', expected_type=dict) or {})
469 username = traverse_obj(media, ('owner', 'username')) or self._search_regex(
470 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"', webpage, 'username', fatal=False)
472 description = (
473 traverse_obj(media, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type=str)
474 or media.get('caption'))
475 if not description:
476 description = self._search_regex(
477 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
478 if description is not None:
479 description = lowercase_escape(description)
481 video_url = media.get('video_url')
482 if not video_url:
483 nodes = traverse_obj(media, ('edge_sidecar_to_children', 'edges', ..., 'node'), expected_type=dict) or []
484 if nodes:
485 return self.playlist_result(
486 self._extract_nodes(nodes, True), video_id,
487 format_field(username, None, 'Post by %s'), description)
489 video_url = self._og_search_video_url(webpage, secure=False)
491 formats = [{
492 'url': video_url,
493 'width': self._get_dimension('width', media, webpage),
494 'height': self._get_dimension('height', media, webpage),
496 dash = traverse_obj(media, ('dash_info', 'video_dash_manifest'))
497 if dash:
498 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash'))
500 comment_data = traverse_obj(media, ('edge_media_to_parent_comment', 'edges'))
501 comments = [{
502 'author': traverse_obj(comment_dict, ('node', 'owner', 'username')),
503 'author_id': traverse_obj(comment_dict, ('node', 'owner', 'id')),
504 'id': traverse_obj(comment_dict, ('node', 'id')),
505 'text': traverse_obj(comment_dict, ('node', 'text')),
506 'timestamp': traverse_obj(comment_dict, ('node', 'created_at'), expected_type=int_or_none),
507 } for comment_dict in comment_data] if comment_data else None
509 display_resources = (
510 media.get('display_resources')
511 or [{'src': media.get(key)} for key in ('display_src', 'display_url')]
512 or [{'src': self._og_search_thumbnail(webpage)}])
513 thumbnails = [{
514 'url': thumbnail['src'],
515 'width': thumbnail.get('config_width'),
516 'height': thumbnail.get('config_height'),
517 } for thumbnail in display_resources if thumbnail.get('src')]
519 return {
520 'id': video_id,
521 'formats': formats,
522 'title': media.get('title') or f'Video by {username}',
523 'description': description,
524 'duration': float_or_none(media.get('video_duration')),
525 'timestamp': traverse_obj(media, 'taken_at_timestamp', 'date', expected_type=int_or_none),
526 'uploader_id': traverse_obj(media, ('owner', 'id')),
527 'uploader': traverse_obj(media, ('owner', 'full_name')),
528 'channel': username,
529 'like_count': self._get_count(media, 'likes', 'preview_like') or str_to_int(self._search_regex(
530 r'data-log-event="likeCountClick"[^>]*>[^\d]*([\d,\.]+)', webpage, 'like count', fatal=False)),
531 'comment_count': self._get_count(media, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
532 'comments': comments,
533 'thumbnails': thumbnails,
534 'http_headers': {
535 'Referer': 'https://www.instagram.com/',
540 class InstagramPlaylistBaseIE(InstagramBaseIE):
541 _gis_tmpl = None # used to cache GIS request type
543 def _parse_graphql(self, webpage, item_id):
544 # Reads a webpage and returns its GraphQL data.
545 return self._parse_json(
546 self._search_regex(
547 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
548 item_id)
550 def _extract_graphql(self, data, url):
551 # Parses GraphQL queries containing videos and generates a playlist.
552 uploader_id = self._match_id(url)
553 csrf_token = data['config']['csrf_token']
554 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
556 cursor = ''
557 for page_num in itertools.count(1):
558 variables = {
559 'first': 12,
560 'after': cursor,
562 variables.update(self._query_vars_for(data))
563 variables = json.dumps(variables)
565 if self._gis_tmpl:
566 gis_tmpls = [self._gis_tmpl]
567 else:
568 gis_tmpls = [
569 f'{rhx_gis}',
571 f'{rhx_gis}:{csrf_token}',
572 '{}:{}:{}'.format(rhx_gis, csrf_token, self.get_param('http_headers')['User-Agent']),
575 # try all of the ways to generate a GIS query, and not only use the
576 # first one that works, but cache it for future requests
577 for gis_tmpl in gis_tmpls:
578 try:
579 json_data = self._download_json(
580 'https://www.instagram.com/graphql/query/', uploader_id,
581 f'Downloading JSON page {page_num}', headers={
582 'X-Requested-With': 'XMLHttpRequest',
583 'X-Instagram-GIS': hashlib.md5(
584 (f'{gis_tmpl}:{variables}').encode()).hexdigest(),
585 }, query={
586 'query_hash': self._QUERY_HASH,
587 'variables': variables,
589 media = self._parse_timeline_from(json_data)
590 self._gis_tmpl = gis_tmpl
591 break
592 except ExtractorError as e:
593 # if it's an error caused by a bad query, and there are
594 # more GIS templates to try, ignore it and keep trying
595 if isinstance(e.cause, HTTPError) and e.cause.status == 403:
596 if gis_tmpl != gis_tmpls[-1]:
597 continue
598 raise
600 nodes = traverse_obj(media, ('edges', ..., 'node'), expected_type=dict) or []
601 if not nodes:
602 break
603 yield from self._extract_nodes(nodes)
605 has_next_page = traverse_obj(media, ('page_info', 'has_next_page'))
606 cursor = traverse_obj(media, ('page_info', 'end_cursor'), expected_type=str)
607 if not has_next_page or not cursor:
608 break
610 def _real_extract(self, url):
611 user_or_tag = self._match_id(url)
612 webpage = self._download_webpage(url, user_or_tag)
613 data = self._parse_graphql(webpage, user_or_tag)
615 self._set_cookie('instagram.com', 'ig_pr', '1')
617 return self.playlist_result(
618 self._extract_graphql(data, url), user_or_tag, user_or_tag)
621 class InstagramUserIE(InstagramPlaylistBaseIE):
622 _WORKING = False
623 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
624 IE_DESC = 'Instagram user profile'
625 IE_NAME = 'instagram:user'
626 _TESTS = [{
627 'url': 'https://instagram.com/porsche',
628 'info_dict': {
629 'id': 'porsche',
630 'title': 'porsche',
632 'playlist_count': 5,
633 'params': {
634 'extract_flat': True,
635 'skip_download': True,
636 'playlistend': 5,
640 _QUERY_HASH = ('42323d64886122307be10013ad2dcc44',)
642 @staticmethod
643 def _parse_timeline_from(data):
644 # extracts the media timeline data from a GraphQL result
645 return data['data']['user']['edge_owner_to_timeline_media']
647 @staticmethod
648 def _query_vars_for(data):
649 # returns a dictionary of variables to add to the timeline query based
650 # on the GraphQL of the original page
651 return {
652 'id': data['entry_data']['ProfilePage'][0]['graphql']['user']['id'],
656 class InstagramTagIE(InstagramPlaylistBaseIE):
657 _VALID_URL = r'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
658 IE_DESC = 'Instagram hashtag search URLs'
659 IE_NAME = 'instagram:tag'
660 _TESTS = [{
661 'url': 'https://instagram.com/explore/tags/lolcats',
662 'info_dict': {
663 'id': 'lolcats',
664 'title': 'lolcats',
666 'playlist_count': 50,
667 'params': {
668 'extract_flat': True,
669 'skip_download': True,
670 'playlistend': 50,
674 _QUERY_HASH = ('f92f56d47dc7a55b606908374b43a314',)
676 @staticmethod
677 def _parse_timeline_from(data):
678 # extracts the media timeline data from a GraphQL result
679 return data['data']['hashtag']['edge_hashtag_to_media']
681 @staticmethod
682 def _query_vars_for(data):
683 # returns a dictionary of variables to add to the timeline query based
684 # on the GraphQL of the original page
685 return {
686 'tag_name':
687 data['entry_data']['TagPage'][0]['graphql']['hashtag']['name'],
691 class InstagramStoryIE(InstagramBaseIE):
692 _VALID_URL = r'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
693 IE_NAME = 'instagram:story'
695 _TESTS = [{
696 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
697 'info_dict': {
698 'id': '18090946048123978',
699 'title': 'Rare',
701 'playlist_mincount': 50,
704 def _real_extract(self, url):
705 username, story_id = self._match_valid_url(url).groups()
706 story_info = self._download_webpage(url, story_id)
707 user_info = self._search_json(r'"user":', story_info, 'user info', story_id, fatal=False)
708 if not user_info:
709 self.raise_login_required('This content is unreachable')
711 user_id = traverse_obj(user_info, 'pk', 'id', expected_type=str)
712 story_info_url = user_id if username != 'highlights' else f'highlight:{story_id}'
713 if not story_info_url: # user id is only mandatory for non-highlights
714 raise ExtractorError('Unable to extract user id')
716 videos = traverse_obj(self._download_json(
717 f'{self._API_BASE_URL}/feed/reels_media/?reel_ids={story_info_url}',
718 story_id, errnote=False, fatal=False, headers=self._API_HEADERS), 'reels')
719 if not videos:
720 self.raise_login_required('You need to log in to access this content')
722 full_name = traverse_obj(videos, (f'highlight:{story_id}', 'user', 'full_name'), (user_id, 'user', 'full_name'))
723 story_title = traverse_obj(videos, (f'highlight:{story_id}', 'title'))
724 if not story_title:
725 story_title = f'Story by {username}'
727 highlights = traverse_obj(videos, (f'highlight:{story_id}', 'items'), (user_id, 'items'))
728 info_data = []
729 for highlight in highlights:
730 highlight_data = self._extract_product(highlight)
731 if highlight_data.get('formats'):
732 info_data.append({
733 'uploader': full_name,
734 'uploader_id': user_id,
735 **filter_dict(highlight_data),
737 return self.playlist_result(info_data, playlist_id=story_id, playlist_title=story_title)