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