]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/instagram.py
[Instagram] Fix extraction when logged in (#2439)
[yt-dlp.git] / yt_dlp / extractor / instagram.py
1 # coding: utf-8
2
3 import itertools
4 import hashlib
5 import json
6 import re
7 import time
8
9 from .common import InfoExtractor
10 from ..compat import (
11 compat_HTTPError,
12 )
13 from ..utils import (
14 ExtractorError,
15 format_field,
16 float_or_none,
17 get_element_by_attribute,
18 int_or_none,
19 lowercase_escape,
20 std_headers,
21 str_or_none,
22 str_to_int,
23 traverse_obj,
24 url_or_none,
25 urlencode_postdata,
26 )
27
28
29 class InstagramBaseIE(InfoExtractor):
30 _NETRC_MACHINE = 'instagram'
31 _IS_LOGGED_IN = False
32
33 def _login(self):
34 username, password = self._get_login_info()
35 if username is None or self._IS_LOGGED_IN:
36 return
37
38 login_webpage = self._download_webpage(
39 'https://www.instagram.com/accounts/login/', None,
40 note='Downloading login webpage', errnote='Failed to download login webpage')
41
42 shared_data = self._parse_json(
43 self._search_regex(
44 r'window\._sharedData\s*=\s*({.+?});',
45 login_webpage, 'shared data', default='{}'),
46 None)
47
48 login = self._download_json('https://www.instagram.com/accounts/login/ajax/', None, note='Logging in', headers={
49 'Accept': '*/*',
50 'X-IG-App-ID': '936619743392459',
51 'X-ASBD-ID': '198387',
52 'X-IG-WWW-Claim': '0',
53 'X-Requested-With': 'XMLHttpRequest',
54 'X-CSRFToken': shared_data['config']['csrf_token'],
55 'X-Instagram-AJAX': shared_data['rollout_hash'],
56 'Referer': 'https://www.instagram.com/',
57 }, data=urlencode_postdata({
58 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
59 'username': username,
60 'queryParams': '{}',
61 'optIntoOneTap': 'false',
62 'stopDeletionNonce': '',
63 'trustedDeviceRecords': '{}',
64 }))
65
66 if not login.get('authenticated'):
67 if login.get('message'):
68 raise ExtractorError(f'Unable to login: {login["message"]}')
69 elif login.get('user'):
70 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected=True)
71 elif login.get('user') is False:
72 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected=True)
73 raise ExtractorError('Unable to login')
74 InstagramBaseIE._IS_LOGGED_IN = True
75
76 def _real_initialize(self):
77 self._login()
78
79 def _get_count(self, media, kind, *keys):
80 return traverse_obj(
81 media, (kind, 'count'), *((f'edge_media_{key}', 'count') for key in keys),
82 expected_type=int_or_none)
83
84 def _get_dimension(self, name, media, webpage=None):
85 return (
86 traverse_obj(media, ('dimensions', name), expected_type=int_or_none)
87 or int_or_none(self._html_search_meta(
88 (f'og:video:{name}', f'video:{name}'), webpage or '', default=None)))
89
90 def _extract_nodes(self, nodes, is_direct=False):
91 for idx, node in enumerate(nodes, start=1):
92 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
93 continue
94
95 video_id = node.get('shortcode')
96
97 if is_direct:
98 info = {
99 'id': video_id or node['id'],
100 'url': node.get('video_url'),
101 'width': self._get_dimension('width', node),
102 'height': self._get_dimension('height', node),
103 'http_headers': {
104 'Referer': 'https://www.instagram.com/',
105 }
106 }
107 elif not video_id:
108 continue
109 else:
110 info = {
111 '_type': 'url',
112 'ie_key': 'Instagram',
113 'id': video_id,
114 'url': f'https://instagram.com/p/{video_id}',
115 }
116
117 yield {
118 **info,
119 'title': node.get('title') or (f'Video {idx}' if is_direct else None),
120 'description': traverse_obj(
121 node, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type=str),
122 'thumbnail': traverse_obj(
123 node, 'display_url', 'thumbnail_src', 'display_src', expected_type=url_or_none),
124 'duration': float_or_none(node.get('video_duration')),
125 'timestamp': int_or_none(node.get('taken_at_timestamp')),
126 'view_count': int_or_none(node.get('video_view_count')),
127 'comment_count': self._get_count(node, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
128 'like_count': self._get_count(node, 'likes', 'preview_like'),
129 }
130
131 def _extract_product_media(self, product_media):
132 media_id = product_media.get('code') or product_media.get('id')
133 vcodec = product_media.get('video_codec')
134 dash_manifest_raw = product_media.get('video_dash_manifest')
135 videos_list = product_media.get('video_versions')
136 if not (dash_manifest_raw or videos_list):
137 return None
138
139 formats = [{
140 'format_id': format.get('id'),
141 'url': format.get('url'),
142 'width': format.get('width'),
143 'height': format.get('height'),
144 'vcodec': vcodec,
145 } for format in videos_list or []]
146 if dash_manifest_raw:
147 formats.extend(self._parse_mpd_formats(self._parse_xml(dash_manifest_raw, media_id), mpd_id='dash'))
148 self._sort_formats(formats)
149
150 thumbnails = [{
151 'url': thumbnail.get('url'),
152 'width': thumbnail.get('width'),
153 'height': thumbnail.get('height')
154 } for thumbnail in traverse_obj(product_media, ('image_versions2', 'candidates')) or []]
155 return {
156 'id': media_id,
157 'duration': float_or_none(product_media.get('video_duration')),
158 'formats': formats,
159 'thumbnails': thumbnails
160 }
161
162 def _extract_product(self, product_info):
163 if isinstance(product_info, list):
164 product_info = product_info[0]
165
166 user_info = product_info.get('user') or {}
167 info_dict = {
168 'id': product_info.get('code') or product_info.get('id'),
169 'title': product_info.get('title') or f'Video by {user_info.get("username")}',
170 'description': traverse_obj(product_info, ('caption', 'text'), expected_type=str_or_none),
171 'timestamp': int_or_none(product_info.get('taken_at')),
172 'channel': user_info.get('username'),
173 'uploader': user_info.get('full_name'),
174 'uploader_id': str_or_none(user_info.get('pk')),
175 'view_count': int_or_none(product_info.get('view_count')),
176 'like_count': int_or_none(product_info.get('like_count')),
177 'comment_count': int_or_none(product_info.get('comment_count')),
178 'http_headers': {
179 'Referer': 'https://www.instagram.com/',
180 }
181 }
182 carousel_media = product_info.get('carousel_media')
183 if carousel_media:
184 return {
185 '_type': 'playlist',
186 **info_dict,
187 'title': f'Post by {user_info.get("username")}',
188 'entries': [{
189 **info_dict,
190 **self._extract_product_media(product_media),
191 } for product_media in carousel_media],
192 }
193
194 return {
195 **info_dict,
196 **self._extract_product_media(product_info)
197 }
198
199
200 class InstagramIOSIE(InfoExtractor):
201 IE_DESC = 'IOS instagram:// URL'
202 _VALID_URL = r'instagram://media\?id=(?P<id>[\d_]+)'
203 _TESTS = [{
204 'url': 'instagram://media?id=482584233761418119',
205 'md5': '0d2da106a9d2631273e192b372806516',
206 'info_dict': {
207 'id': 'aye83DjauH',
208 'ext': 'mp4',
209 'title': 'Video by naomipq',
210 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
211 'thumbnail': r're:^https?://.*\.jpg',
212 'duration': 0,
213 'timestamp': 1371748545,
214 'upload_date': '20130620',
215 'uploader_id': 'naomipq',
216 'uploader': 'B E A U T Y F O R A S H E S',
217 'like_count': int,
218 'comment_count': int,
219 'comments': list,
220 },
221 'add_ie': ['Instagram']
222 }]
223
224 def _get_id(self, id):
225 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
226 chrs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
227 media_id = int(id.split('_')[0])
228 shortened_id = ''
229 while media_id > 0:
230 r = media_id % 64
231 media_id = (media_id - r) // 64
232 shortened_id = chrs[r] + shortened_id
233 return shortened_id
234
235 def _real_extract(self, url):
236 return {
237 '_type': 'url_transparent',
238 'url': f'http://instagram.com/tv/{self._get_id(self._match_id(url))}/',
239 'ie_key': 'Instagram',
240 }
241
242
243 class InstagramIE(InstagramBaseIE):
244 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
245 _TESTS = [{
246 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
247 'md5': '0d2da106a9d2631273e192b372806516',
248 'info_dict': {
249 'id': 'aye83DjauH',
250 'ext': 'mp4',
251 'title': 'Video by naomipq',
252 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
253 'thumbnail': r're:^https?://.*\.jpg',
254 'duration': 0,
255 'timestamp': 1371748545,
256 'upload_date': '20130620',
257 'uploader_id': '2815873',
258 'uploader': 'B E A U T Y F O R A S H E S',
259 'channel': 'naomipq',
260 'like_count': int,
261 'comment_count': int,
262 'comments': list,
263 },
264 }, {
265 # missing description
266 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
267 'info_dict': {
268 'id': 'BA-pQFBG8HZ',
269 'ext': 'mp4',
270 'title': 'Video by britneyspears',
271 'thumbnail': r're:^https?://.*\.jpg',
272 'duration': 0,
273 'timestamp': 1453760977,
274 'upload_date': '20160125',
275 'uploader_id': '12246775',
276 'uploader': 'Britney Spears',
277 'channel': 'britneyspears',
278 'like_count': int,
279 'comment_count': int,
280 'comments': list,
281 },
282 'params': {
283 'skip_download': True,
284 },
285 }, {
286 # multi video post
287 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
288 'playlist': [{
289 'info_dict': {
290 'id': 'BQ0dSaohpPW',
291 'ext': 'mp4',
292 'title': 'Video 1',
293 },
294 }, {
295 'info_dict': {
296 'id': 'BQ0dTpOhuHT',
297 'ext': 'mp4',
298 'title': 'Video 2',
299 },
300 }, {
301 'info_dict': {
302 'id': 'BQ0dT7RBFeF',
303 'ext': 'mp4',
304 'title': 'Video 3',
305 },
306 }],
307 'info_dict': {
308 'id': 'BQ0eAlwhDrw',
309 'title': 'Post by instagram',
310 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
311 },
312 }, {
313 # IGTV
314 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
315 'info_dict': {
316 'id': 'BkfuX9UB-eK',
317 'ext': 'mp4',
318 'title': 'Fingerboarding Tricks with @cass.fb',
319 'thumbnail': r're:^https?://.*\.jpg',
320 'duration': 53.83,
321 'timestamp': 1530032919,
322 'upload_date': '20180626',
323 'uploader_id': '25025320',
324 'uploader': 'Instagram',
325 'channel': 'instagram',
326 'like_count': int,
327 'comment_count': int,
328 'comments': list,
329 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
330 }
331 }, {
332 'url': 'https://instagram.com/p/-Cmh1cukG2/',
333 'only_matching': True,
334 }, {
335 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
336 'only_matching': True,
337 }, {
338 'url': 'https://www.instagram.com/tv/aye83DjauH/',
339 'only_matching': True,
340 }, {
341 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
342 'only_matching': True,
343 }, {
344 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
345 'only_matching': True,
346 }]
347
348 @staticmethod
349 def _extract_embed_url(webpage):
350 mobj = re.search(
351 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
352 webpage)
353 if mobj:
354 return mobj.group('url')
355
356 blockquote_el = get_element_by_attribute(
357 'class', 'instagram-media', webpage)
358 if blockquote_el is None:
359 return
360
361 mobj = re.search(
362 r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
363 if mobj:
364 return mobj.group('link')
365
366 def _real_extract(self, url):
367 video_id, url = self._match_valid_url(url).group('id', 'url')
368 webpage, urlh = self._download_webpage_handle(url, video_id)
369 if 'www.instagram.com/accounts/login' in urlh.geturl():
370 self.report_warning('Main webpage is locked behind the login page. '
371 'Retrying with embed webpage (Note that some metadata might be missing)')
372 webpage = self._download_webpage(
373 'https://www.instagram.com/p/%s/embed/' % video_id, video_id, note='Downloading embed webpage')
374
375 shared_data = self._parse_json(
376 self._search_regex(
377 r'window\._sharedData\s*=\s*({.+?});',
378 webpage, 'shared data', default='{}'),
379 video_id, fatal=False)
380 media = traverse_obj(
381 shared_data,
382 ('entry_data', 'PostPage', 0, 'graphql', 'shortcode_media'),
383 ('entry_data', 'PostPage', 0, 'media'),
384 expected_type=dict)
385
386 # _sharedData.entry_data.PostPage is empty when authenticated (see
387 # https://github.com/ytdl-org/youtube-dl/pull/22880)
388 if not media:
389 additional_data = self._parse_json(
390 self._search_regex(
391 r'window\.__additionalDataLoaded\s*\(\s*[^,]+,\s*({.+?})\s*\);',
392 webpage, 'additional data', default='{}'),
393 video_id, fatal=False)
394 product_item = traverse_obj(additional_data, ('items', 0), expected_type=dict)
395 if product_item:
396 return self._extract_product(product_item)
397 media = traverse_obj(additional_data, ('graphql', 'shortcode_media'), 'shortcode_media', expected_type=dict) or {}
398
399 if not media and 'www.instagram.com/accounts/login' in urlh.geturl():
400 self.raise_login_required('You need to log in to access this content')
401
402 username = traverse_obj(media, ('owner', 'username')) or self._search_regex(
403 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"', webpage, 'username', fatal=False)
404
405 description = (
406 traverse_obj(media, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type=str)
407 or media.get('caption'))
408 if not description:
409 description = self._search_regex(
410 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
411 if description is not None:
412 description = lowercase_escape(description)
413
414 video_url = media.get('video_url')
415 if not video_url:
416 nodes = traverse_obj(media, ('edge_sidecar_to_children', 'edges', ..., 'node'), expected_type=dict) or []
417 if nodes:
418 return self.playlist_result(
419 self._extract_nodes(nodes, True), video_id,
420 format_field(username, template='Post by %s'), description)
421
422 video_url = self._og_search_video_url(webpage, secure=False)
423
424 formats = [{
425 'url': video_url,
426 'width': self._get_dimension('width', media, webpage),
427 'height': self._get_dimension('height', media, webpage),
428 }]
429 dash = traverse_obj(media, ('dash_info', 'video_dash_manifest'))
430 if dash:
431 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash'))
432 self._sort_formats(formats)
433
434 comment_data = traverse_obj(media, ('edge_media_to_parent_comment', 'edges'))
435 comments = [{
436 'author': traverse_obj(comment_dict, ('node', 'owner', 'username')),
437 'author_id': traverse_obj(comment_dict, ('node', 'owner', 'id')),
438 'id': traverse_obj(comment_dict, ('node', 'id')),
439 'text': traverse_obj(comment_dict, ('node', 'text')),
440 'timestamp': traverse_obj(comment_dict, ('node', 'created_at'), expected_type=int_or_none),
441 } for comment_dict in comment_data] if comment_data else None
442
443 display_resources = (
444 media.get('display_resources')
445 or [{'src': media.get(key)} for key in ('display_src', 'display_url')]
446 or [{'src': self._og_search_thumbnail(webpage)}])
447 thumbnails = [{
448 'url': thumbnail['src'],
449 'width': thumbnail.get('config_width'),
450 'height': thumbnail.get('config_height'),
451 } for thumbnail in display_resources if thumbnail.get('src')]
452
453 return {
454 'id': video_id,
455 'formats': formats,
456 'title': media.get('title') or 'Video by %s' % username,
457 'description': description,
458 'duration': float_or_none(media.get('video_duration')),
459 'timestamp': traverse_obj(media, 'taken_at_timestamp', 'date', expected_type=int_or_none),
460 'uploader_id': traverse_obj(media, ('owner', 'id')),
461 'uploader': traverse_obj(media, ('owner', 'full_name')),
462 'channel': username,
463 'like_count': self._get_count(media, 'likes', 'preview_like') or str_to_int(self._search_regex(
464 r'data-log-event="likeCountClick"[^>]*>[^\d]*([\d,\.]+)', webpage, 'like count', fatal=False)),
465 'comment_count': self._get_count(media, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
466 'comments': comments,
467 'thumbnails': thumbnails,
468 'http_headers': {
469 'Referer': 'https://www.instagram.com/',
470 }
471 }
472
473
474 class InstagramPlaylistBaseIE(InstagramBaseIE):
475 _gis_tmpl = None # used to cache GIS request type
476
477 def _parse_graphql(self, webpage, item_id):
478 # Reads a webpage and returns its GraphQL data.
479 return self._parse_json(
480 self._search_regex(
481 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
482 item_id)
483
484 def _extract_graphql(self, data, url):
485 # Parses GraphQL queries containing videos and generates a playlist.
486 uploader_id = self._match_id(url)
487 csrf_token = data['config']['csrf_token']
488 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
489
490 cursor = ''
491 for page_num in itertools.count(1):
492 variables = {
493 'first': 12,
494 'after': cursor,
495 }
496 variables.update(self._query_vars_for(data))
497 variables = json.dumps(variables)
498
499 if self._gis_tmpl:
500 gis_tmpls = [self._gis_tmpl]
501 else:
502 gis_tmpls = [
503 '%s' % rhx_gis,
504 '',
505 '%s:%s' % (rhx_gis, csrf_token),
506 '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent']),
507 ]
508
509 # try all of the ways to generate a GIS query, and not only use the
510 # first one that works, but cache it for future requests
511 for gis_tmpl in gis_tmpls:
512 try:
513 json_data = self._download_json(
514 'https://www.instagram.com/graphql/query/', uploader_id,
515 'Downloading JSON page %d' % page_num, headers={
516 'X-Requested-With': 'XMLHttpRequest',
517 'X-Instagram-GIS': hashlib.md5(
518 ('%s:%s' % (gis_tmpl, variables)).encode('utf-8')).hexdigest(),
519 }, query={
520 'query_hash': self._QUERY_HASH,
521 'variables': variables,
522 })
523 media = self._parse_timeline_from(json_data)
524 self._gis_tmpl = gis_tmpl
525 break
526 except ExtractorError as e:
527 # if it's an error caused by a bad query, and there are
528 # more GIS templates to try, ignore it and keep trying
529 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
530 if gis_tmpl != gis_tmpls[-1]:
531 continue
532 raise
533
534 nodes = traverse_obj(media, ('edges', ..., 'node'), expected_type=dict) or []
535 if not nodes:
536 break
537 yield from self._extract_nodes(nodes)
538
539 has_next_page = traverse_obj(media, ('page_info', 'has_next_page'))
540 cursor = traverse_obj(media, ('page_info', 'end_cursor'), expected_type=str)
541 if not has_next_page or not cursor:
542 break
543
544 def _real_extract(self, url):
545 user_or_tag = self._match_id(url)
546 webpage = self._download_webpage(url, user_or_tag)
547 data = self._parse_graphql(webpage, user_or_tag)
548
549 self._set_cookie('instagram.com', 'ig_pr', '1')
550
551 return self.playlist_result(
552 self._extract_graphql(data, url), user_or_tag, user_or_tag)
553
554
555 class InstagramUserIE(InstagramPlaylistBaseIE):
556 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
557 IE_DESC = 'Instagram user profile'
558 IE_NAME = 'instagram:user'
559 _TESTS = [{
560 'url': 'https://instagram.com/porsche',
561 'info_dict': {
562 'id': 'porsche',
563 'title': 'porsche',
564 },
565 'playlist_count': 5,
566 'params': {
567 'extract_flat': True,
568 'skip_download': True,
569 'playlistend': 5,
570 }
571 }]
572
573 _QUERY_HASH = '42323d64886122307be10013ad2dcc44',
574
575 @staticmethod
576 def _parse_timeline_from(data):
577 # extracts the media timeline data from a GraphQL result
578 return data['data']['user']['edge_owner_to_timeline_media']
579
580 @staticmethod
581 def _query_vars_for(data):
582 # returns a dictionary of variables to add to the timeline query based
583 # on the GraphQL of the original page
584 return {
585 'id': data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
586 }
587
588
589 class InstagramTagIE(InstagramPlaylistBaseIE):
590 _VALID_URL = r'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
591 IE_DESC = 'Instagram hashtag search URLs'
592 IE_NAME = 'instagram:tag'
593 _TESTS = [{
594 'url': 'https://instagram.com/explore/tags/lolcats',
595 'info_dict': {
596 'id': 'lolcats',
597 'title': 'lolcats',
598 },
599 'playlist_count': 50,
600 'params': {
601 'extract_flat': True,
602 'skip_download': True,
603 'playlistend': 50,
604 }
605 }]
606
607 _QUERY_HASH = 'f92f56d47dc7a55b606908374b43a314',
608
609 @staticmethod
610 def _parse_timeline_from(data):
611 # extracts the media timeline data from a GraphQL result
612 return data['data']['hashtag']['edge_hashtag_to_media']
613
614 @staticmethod
615 def _query_vars_for(data):
616 # returns a dictionary of variables to add to the timeline query based
617 # on the GraphQL of the original page
618 return {
619 'tag_name':
620 data['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
621 }
622
623
624 class InstagramStoryIE(InstagramBaseIE):
625 _VALID_URL = r'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
626 IE_NAME = 'instagram:story'
627
628 _TESTS = [{
629 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
630 'info_dict': {
631 'id': '18090946048123978',
632 'title': 'Rare',
633 },
634 'playlist_mincount': 50
635 }]
636
637 def _real_extract(self, url):
638 username, story_id = self._match_valid_url(url).groups()
639
640 story_info_url = f'{username}/{story_id}/?__a=1' if username == 'highlights' else f'{username}/?__a=1'
641 story_info = self._download_json(f'https://www.instagram.com/stories/{story_info_url}', story_id, headers={
642 'X-IG-App-ID': 936619743392459,
643 'X-ASBD-ID': 198387,
644 'X-IG-WWW-Claim': 0,
645 'X-Requested-With': 'XMLHttpRequest',
646 'Referer': url,
647 })
648 user_id = story_info['user']['id']
649 highlight_title = traverse_obj(story_info, ('highlight', 'title'))
650
651 story_info_url = user_id if username != 'highlights' else f'highlight:{story_id}'
652 videos = self._download_json(f'https://i.instagram.com/api/v1/feed/reels_media/?reel_ids={story_info_url}', story_id, headers={
653 'X-IG-App-ID': 936619743392459,
654 'X-ASBD-ID': 198387,
655 'X-IG-WWW-Claim': 0,
656 })['reels']
657
658 full_name = traverse_obj(videos, ('user', 'full_name'))
659
660 user_info = {}
661 if not (username and username != 'highlights' and full_name):
662 user_info = self._download_json(
663 f'https://i.instagram.com/api/v1/users/{user_id}/info/', story_id, headers={
664 '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)',
665 }, note='Downloading user info')
666
667 username = traverse_obj(user_info, ('user', 'username')) or username
668 full_name = traverse_obj(user_info, ('user', 'full_name')) or full_name
669
670 highlights = traverse_obj(videos, (f'highlight:{story_id}', 'items'), (str(user_id), 'items'))
671 return self.playlist_result([{
672 **self._extract_product(highlight),
673 'title': f'Story by {username}',
674 'uploader': full_name,
675 'uploader_id': user_id,
676 } for highlight in highlights], playlist_id=story_id, playlist_title=highlight_title)