]> jfr.im git - yt-dlp.git/blame - youtube_dlc/extractor/instagram.py
Update to ytdl-2021.01.03
[yt-dlp.git] / youtube_dlc / extractor / instagram.py
CommitLineData
0de668af
JMF
1from __future__ import unicode_literals
2
cba5d1b6 3import itertools
315ab3d5 4import hashlib
27b1c73f 5import json
59fc531f
JMF
6import re
7
8from .common import InfoExtractor
238d42cf
S
9from ..compat import (
10 compat_str,
11 compat_HTTPError,
12)
e1ec9330 13from ..utils import (
238d42cf 14 ExtractorError,
c4096e8a 15 get_element_by_attribute,
e1ec9330 16 int_or_none,
87696e78 17 lowercase_escape,
238d42cf 18 std_headers,
98960c91 19 try_get,
3052a30d 20 url_or_none,
e1ec9330 21)
59fc531f 22
0de668af 23
59fc531f 24class InstagramIE(InfoExtractor):
29f7c58a 25 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
4479600d 26 _TESTS = [{
fc6e75dd 27 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
0de668af
JMF
28 'md5': '0d2da106a9d2631273e192b372806516',
29 'info_dict': {
30 'id': 'aye83DjauH',
31 'ext': 'mp4',
0de668af
JMF
32 'title': 'Video by naomipq',
33 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
ec85ded8 34 'thumbnail': r're:^https?://.*\.jpg',
98960c91
S
35 'timestamp': 1371748545,
36 'upload_date': '20130620',
37 'uploader_id': 'naomipq',
29f7c58a 38 'uploader': 'B E A U T Y F O R A S H E S',
98960c91
S
39 'like_count': int,
40 'comment_count': int,
a56e74e2 41 'comments': list,
98960c91 42 },
fb4b3458
S
43 }, {
44 # missing description
45 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
46 'info_dict': {
47 'id': 'BA-pQFBG8HZ',
48 'ext': 'mp4',
fb4b3458 49 'title': 'Video by britneyspears',
ec85ded8 50 'thumbnail': r're:^https?://.*\.jpg',
98960c91
S
51 'timestamp': 1453760977,
52 'upload_date': '20160125',
53 'uploader_id': 'britneyspears',
54 'uploader': 'Britney Spears',
55 'like_count': int,
56 'comment_count': int,
a56e74e2 57 'comments': list,
fb4b3458
S
58 },
59 'params': {
60 'skip_download': True,
61 },
ada77fa5
S
62 }, {
63 # multi video post
64 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
65 'playlist': [{
66 'info_dict': {
67 'id': 'BQ0dSaohpPW',
68 'ext': 'mp4',
69 'title': 'Video 1',
70 },
71 }, {
72 'info_dict': {
73 'id': 'BQ0dTpOhuHT',
74 'ext': 'mp4',
75 'title': 'Video 2',
76 },
77 }, {
78 'info_dict': {
79 'id': 'BQ0dT7RBFeF',
80 'ext': 'mp4',
81 'title': 'Video 3',
82 },
83 }],
84 'info_dict': {
85 'id': 'BQ0eAlwhDrw',
86 'title': 'Post by instagram',
87 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
88 },
4479600d
S
89 }, {
90 'url': 'https://instagram.com/p/-Cmh1cukG2/',
91 'only_matching': True,
0dafea02
S
92 }, {
93 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
94 'only_matching': True,
edb2820c
RA
95 }, {
96 'url': 'https://www.instagram.com/tv/aye83DjauH/',
97 'only_matching': True,
29f7c58a 98 }, {
99 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
100 'only_matching': True,
4479600d 101 }]
59fc531f 102
c4096e8a
YCH
103 @staticmethod
104 def _extract_embed_url(webpage):
c23533a1
S
105 mobj = re.search(
106 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
107 webpage)
108 if mobj:
109 return mobj.group('url')
110
c4096e8a
YCH
111 blockquote_el = get_element_by_attribute(
112 'class', 'instagram-media', webpage)
113 if blockquote_el is None:
114 return
115
116 mobj = re.search(
117 r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
118 if mobj:
119 return mobj.group('link')
120
59fc531f 121 def _real_extract(self, url):
0dafea02
S
122 mobj = re.match(self._VALID_URL, url)
123 video_id = mobj.group('id')
124 url = mobj.group('url')
d2d8248f 125
59fc531f 126 webpage = self._download_webpage(url, video_id)
98960c91 127
29f7c58a 128 (media, video_url, description, thumbnail, timestamp, uploader,
18848d22 129 uploader_id, like_count, comment_count, comments, height,
29f7c58a 130 width) = [None] * 12
131
132 shared_data = self._parse_json(
133 self._search_regex(
134 r'window\._sharedData\s*=\s*({.+?});',
135 webpage, 'shared data', default='{}'),
136 video_id, fatal=False)
98960c91
S
137 if shared_data:
138 media = try_get(
18848d22 139 shared_data,
29f7c58a 140 (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
141 lambda x: x['entry_data']['PostPage'][0]['media']),
18848d22 142 dict)
29f7c58a 143 # _sharedData.entry_data.PostPage is empty when authenticated (see
144 # https://github.com/ytdl-org/youtube-dl/pull/22880)
145 if not media:
146 additional_data = self._parse_json(
147 self._search_regex(
148 r'window\.__additionalDataLoaded\s*\(\s*[^,]+,\s*({.+?})\s*\)\s*;',
149 webpage, 'additional data', default='{}'),
150 video_id, fatal=False)
151 if additional_data:
152 media = try_get(
153 additional_data, lambda x: x['graphql']['shortcode_media'],
154 dict)
155 if media:
156 video_url = media.get('video_url')
157 height = int_or_none(media.get('dimensions', {}).get('height'))
158 width = int_or_none(media.get('dimensions', {}).get('width'))
159 description = try_get(
160 media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
161 compat_str) or media.get('caption')
162 thumbnail = media.get('display_src') or media.get('display_url')
163 timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
164 uploader = media.get('owner', {}).get('full_name')
165 uploader_id = media.get('owner', {}).get('username')
166
167 def get_count(keys, kind):
168 if not isinstance(keys, (list, tuple)):
169 keys = [keys]
170 for key in keys:
171 count = int_or_none(try_get(
9cbd4dda
S
172 media, (lambda x: x['edge_media_%s' % key]['count'],
173 lambda x: x['%ss' % kind]['count'])))
29f7c58a 174 if count is not None:
175 return count
176 like_count = get_count('preview_like', 'like')
177 comment_count = get_count(
178 ('preview_comment', 'to_comment', 'to_parent_comment'), 'comment')
179
180 comments = [{
181 'author': comment.get('user', {}).get('username'),
182 'author_id': comment.get('user', {}).get('id'),
183 'id': comment.get('id'),
184 'text': comment.get('text'),
185 'timestamp': int_or_none(comment.get('created_at')),
186 } for comment in media.get(
187 'comments', {}).get('nodes', []) if comment.get('text')]
188 if not video_url:
189 edges = try_get(
190 media, lambda x: x['edge_sidecar_to_children']['edges'],
191 list) or []
192 if edges:
193 entries = []
194 for edge_num, edge in enumerate(edges, start=1):
195 node = try_get(edge, lambda x: x['node'], dict)
196 if not node:
197 continue
198 node_video_url = url_or_none(node.get('video_url'))
199 if not node_video_url:
200 continue
201 entries.append({
202 'id': node.get('shortcode') or node['id'],
203 'title': 'Video %d' % edge_num,
204 'url': node_video_url,
205 'thumbnail': node.get('display_url'),
206 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
207 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
208 'view_count': int_or_none(node.get('video_view_count')),
209 })
210 return self.playlist_result(
211 entries, video_id,
212 'Post by %s' % uploader_id if uploader_id else None,
213 description)
98960c91
S
214
215 if not video_url:
216 video_url = self._og_search_video_url(webpage, secure=False)
217
16097822
DR
218 formats = [{
219 'url': video_url,
220 'width': width,
221 'height': height,
222 }]
223
98960c91
S
224 if not uploader_id:
225 uploader_id = self._search_regex(
226 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
227 webpage, 'uploader id', fatal=False)
228
229 if not description:
230 description = self._search_regex(
231 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
232 if description is not None:
233 description = lowercase_escape(description)
234
235 if not thumbnail:
236 thumbnail = self._og_search_thumbnail(webpage)
59fc531f 237
0de668af
JMF
238 return {
239 'id': video_id,
16097822 240 'formats': formats,
0de668af
JMF
241 'ext': 'mp4',
242 'title': 'Video by %s' % uploader_id,
98960c91
S
243 'description': description,
244 'thumbnail': thumbnail,
245 'timestamp': timestamp,
0de668af 246 'uploader_id': uploader_id,
98960c91
S
247 'uploader': uploader,
248 'like_count': like_count,
249 'comment_count': comment_count,
a56e74e2 250 'comments': comments,
0de668af 251 }
ea38e55f
PH
252
253
31fbedc0 254class InstagramPlaylistIE(InfoExtractor):
255 # A superclass for handling any kind of query based on GraphQL which
256 # results in a playlist.
257
258 _gis_tmpl = None # used to cache GIS request type
ea38e55f 259
31fbedc0 260 def _parse_graphql(self, webpage, item_id):
261 # Reads a webpage and returns its GraphQL data.
262 return self._parse_json(
263 self._search_regex(
264 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
265 item_id)
238d42cf 266
31fbedc0 267 def _extract_graphql(self, data, url):
268 # Parses GraphQL queries containing videos and generates a playlist.
27b1c73f 269 def get_count(suffix):
5fc12b95 270 return int_or_none(try_get(
27b1c73f
RA
271 node, lambda x: x['edge_media_' + suffix]['count']))
272
31fbedc0 273 uploader_id = self._match_id(url)
dd9aea8c
S
274 csrf_token = data['config']['csrf_token']
275 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
276
cba5d1b6
S
277 cursor = ''
278 for page_num in itertools.count(1):
31fbedc0 279 variables = {
9b3036bd 280 'first': 12,
dd9aea8c 281 'after': cursor,
31fbedc0 282 }
283 variables.update(self._query_vars_for(data))
284 variables = json.dumps(variables)
238d42cf
S
285
286 if self._gis_tmpl:
287 gis_tmpls = [self._gis_tmpl]
288 else:
289 gis_tmpls = [
290 '%s' % rhx_gis,
291 '',
292 '%s:%s' % (rhx_gis, csrf_token),
293 '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent']),
294 ]
295
31fbedc0 296 # try all of the ways to generate a GIS query, and not only use the
297 # first one that works, but cache it for future requests
238d42cf
S
298 for gis_tmpl in gis_tmpls:
299 try:
31fbedc0 300 json_data = self._download_json(
238d42cf
S
301 'https://www.instagram.com/graphql/query/', uploader_id,
302 'Downloading JSON page %d' % page_num, headers={
303 'X-Requested-With': 'XMLHttpRequest',
304 'X-Instagram-GIS': hashlib.md5(
305 ('%s:%s' % (gis_tmpl, variables)).encode('utf-8')).hexdigest(),
306 }, query={
31fbedc0 307 'query_hash': self._QUERY_HASH,
238d42cf 308 'variables': variables,
31fbedc0 309 })
310 media = self._parse_timeline_from(json_data)
238d42cf
S
311 self._gis_tmpl = gis_tmpl
312 break
313 except ExtractorError as e:
31fbedc0 314 # if it's an error caused by a bad query, and there are
315 # more GIS templates to try, ignore it and keep trying
238d42cf
S
316 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
317 if gis_tmpl != gis_tmpls[-1]:
318 continue
319 raise
cba5d1b6
S
320
321 edges = media.get('edges')
322 if not edges or not isinstance(edges, list):
323 break
324
325 for edge in edges:
326 node = edge.get('node')
327 if not node or not isinstance(node, dict):
328 continue
329 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
330 continue
331 video_id = node.get('shortcode')
332 if not video_id:
333 continue
334
335 info = self.url_result(
336 'https://instagram.com/p/%s/' % video_id,
337 ie=InstagramIE.ie_key(), video_id=video_id)
338
339 description = try_get(
340 node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
341 compat_str)
342 thumbnail = node.get('thumbnail_src') or node.get('display_src')
343 timestamp = int_or_none(node.get('taken_at_timestamp'))
344
345 comment_count = get_count('to_comment')
346 like_count = get_count('preview_like')
347 view_count = int_or_none(node.get('video_view_count'))
348
349 info.update({
350 'description': description,
351 'thumbnail': thumbnail,
352 'timestamp': timestamp,
353 'comment_count': comment_count,
354 'like_count': like_count,
355 'view_count': view_count,
ea38e55f 356 })
cba5d1b6
S
357
358 yield info
359
360 page_info = media.get('page_info')
361 if not page_info or not isinstance(page_info, dict):
362 break
363
364 has_next_page = page_info.get('has_next_page')
365 if not has_next_page:
366 break
367
368 cursor = page_info.get('end_cursor')
369 if not cursor or not isinstance(cursor, compat_str):
370 break
5fc12b95
S
371
372 def _real_extract(self, url):
31fbedc0 373 user_or_tag = self._match_id(url)
374 webpage = self._download_webpage(url, user_or_tag)
375 data = self._parse_graphql(webpage, user_or_tag)
dd9aea8c 376
31fbedc0 377 self._set_cookie('instagram.com', 'ig_pr', '1')
dd9aea8c 378
5fc12b95 379 return self.playlist_result(
31fbedc0 380 self._extract_graphql(data, url), user_or_tag, user_or_tag)
381
382
383class InstagramUserIE(InstagramPlaylistIE):
384 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
385 IE_DESC = 'Instagram user profile'
386 IE_NAME = 'instagram:user'
387 _TEST = {
388 'url': 'https://instagram.com/porsche',
389 'info_dict': {
390 'id': 'porsche',
391 'title': 'porsche',
392 },
393 'playlist_count': 5,
394 'params': {
395 'extract_flat': True,
396 'skip_download': True,
397 'playlistend': 5,
398 }
399 }
400
401 _QUERY_HASH = '42323d64886122307be10013ad2dcc44',
402
403 @staticmethod
404 def _parse_timeline_from(data):
405 # extracts the media timeline data from a GraphQL result
406 return data['data']['user']['edge_owner_to_timeline_media']
407
408 @staticmethod
409 def _query_vars_for(data):
410 # returns a dictionary of variables to add to the timeline query based
411 # on the GraphQL of the original page
412 return {
413 'id': data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
414 }
415
416
417class InstagramTagIE(InstagramPlaylistIE):
418 _VALID_URL = r'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
419 IE_DESC = 'Instagram hashtag search'
420 IE_NAME = 'instagram:tag'
421 _TEST = {
422 'url': 'https://instagram.com/explore/tags/lolcats',
423 'info_dict': {
424 'id': 'lolcats',
425 'title': 'lolcats',
426 },
427 'playlist_count': 50,
428 'params': {
429 'extract_flat': True,
430 'skip_download': True,
431 'playlistend': 50,
432 }
433 }
434
435 _QUERY_HASH = 'f92f56d47dc7a55b606908374b43a314',
436
437 @staticmethod
438 def _parse_timeline_from(data):
439 # extracts the media timeline data from a GraphQL result
440 return data['data']['hashtag']['edge_hashtag_to_media']
441
442 @staticmethod
443 def _query_vars_for(data):
444 # returns a dictionary of variables to add to the timeline query based
445 # on the GraphQL of the original page
446 return {
447 'tag_name':
448 data['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
449 }