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