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