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