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