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