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