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