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