[instagram:user] Simplify signing (#16119)
[youtube-dl] / 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 compat_str
10 from ..utils import (
11     get_element_by_attribute,
12     int_or_none,
13     lowercase_escape,
14     std_headers,
15     try_get,
16 )
17
18
19 class InstagramIE(InfoExtractor):
20     _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/p/(?P<id>[^/?#&]+))'
21     _TESTS = [{
22         'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
23         'md5': '0d2da106a9d2631273e192b372806516',
24         'info_dict': {
25             'id': 'aye83DjauH',
26             'ext': 'mp4',
27             'title': 'Video by naomipq',
28             'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
29             'thumbnail': r're:^https?://.*\.jpg',
30             'timestamp': 1371748545,
31             'upload_date': '20130620',
32             'uploader_id': 'naomipq',
33             'uploader': 'Naomi Leonor Phan-Quang',
34             'like_count': int,
35             'comment_count': int,
36             'comments': list,
37         },
38     }, {
39         # missing description
40         'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
41         'info_dict': {
42             'id': 'BA-pQFBG8HZ',
43             'ext': 'mp4',
44             'title': 'Video by britneyspears',
45             'thumbnail': r're:^https?://.*\.jpg',
46             'timestamp': 1453760977,
47             'upload_date': '20160125',
48             'uploader_id': 'britneyspears',
49             'uploader': 'Britney Spears',
50             'like_count': int,
51             'comment_count': int,
52             'comments': list,
53         },
54         'params': {
55             'skip_download': True,
56         },
57     }, {
58         # multi video post
59         'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
60         'playlist': [{
61             'info_dict': {
62                 'id': 'BQ0dSaohpPW',
63                 'ext': 'mp4',
64                 'title': 'Video 1',
65             },
66         }, {
67             'info_dict': {
68                 'id': 'BQ0dTpOhuHT',
69                 'ext': 'mp4',
70                 'title': 'Video 2',
71             },
72         }, {
73             'info_dict': {
74                 'id': 'BQ0dT7RBFeF',
75                 'ext': 'mp4',
76                 'title': 'Video 3',
77             },
78         }],
79         'info_dict': {
80             'id': 'BQ0eAlwhDrw',
81             'title': 'Post by instagram',
82             'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
83         },
84     }, {
85         'url': 'https://instagram.com/p/-Cmh1cukG2/',
86         'only_matching': True,
87     }, {
88         'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
89         'only_matching': True,
90     }]
91
92     @staticmethod
93     def _extract_embed_url(webpage):
94         mobj = re.search(
95             r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
96             webpage)
97         if mobj:
98             return mobj.group('url')
99
100         blockquote_el = get_element_by_attribute(
101             'class', 'instagram-media', webpage)
102         if blockquote_el is None:
103             return
104
105         mobj = re.search(
106             r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
107         if mobj:
108             return mobj.group('link')
109
110     def _real_extract(self, url):
111         mobj = re.match(self._VALID_URL, url)
112         video_id = mobj.group('id')
113         url = mobj.group('url')
114
115         webpage = self._download_webpage(url, video_id)
116
117         (video_url, description, thumbnail, timestamp, uploader,
118          uploader_id, like_count, comment_count, comments, height,
119          width) = [None] * 11
120
121         shared_data = self._parse_json(
122             self._search_regex(
123                 r'window\._sharedData\s*=\s*({.+?});',
124                 webpage, 'shared data', default='{}'),
125             video_id, fatal=False)
126         if shared_data:
127             media = try_get(
128                 shared_data,
129                 (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
130                  lambda x: x['entry_data']['PostPage'][0]['media']),
131                 dict)
132             if media:
133                 video_url = media.get('video_url')
134                 height = int_or_none(media.get('dimensions', {}).get('height'))
135                 width = int_or_none(media.get('dimensions', {}).get('width'))
136                 description = try_get(
137                     media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
138                     compat_str) or media.get('caption')
139                 thumbnail = media.get('display_src')
140                 timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
141                 uploader = media.get('owner', {}).get('full_name')
142                 uploader_id = media.get('owner', {}).get('username')
143
144                 def get_count(key, kind):
145                     return int_or_none(try_get(
146                         media, (lambda x: x['edge_media_%s' % key]['count'],
147                                 lambda x: x['%ss' % kind]['count'])))
148                 like_count = get_count('preview_like', 'like')
149                 comment_count = get_count('to_comment', 'comment')
150
151                 comments = [{
152                     'author': comment.get('user', {}).get('username'),
153                     'author_id': comment.get('user', {}).get('id'),
154                     'id': comment.get('id'),
155                     'text': comment.get('text'),
156                     'timestamp': int_or_none(comment.get('created_at')),
157                 } for comment in media.get(
158                     'comments', {}).get('nodes', []) if comment.get('text')]
159                 if not video_url:
160                     edges = try_get(
161                         media, lambda x: x['edge_sidecar_to_children']['edges'],
162                         list) or []
163                     if edges:
164                         entries = []
165                         for edge_num, edge in enumerate(edges, start=1):
166                             node = try_get(edge, lambda x: x['node'], dict)
167                             if not node:
168                                 continue
169                             node_video_url = try_get(node, lambda x: x['video_url'], compat_str)
170                             if not node_video_url:
171                                 continue
172                             entries.append({
173                                 'id': node.get('shortcode') or node['id'],
174                                 'title': 'Video %d' % edge_num,
175                                 'url': node_video_url,
176                                 'thumbnail': node.get('display_url'),
177                                 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
178                                 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
179                                 'view_count': int_or_none(node.get('video_view_count')),
180                             })
181                         return self.playlist_result(
182                             entries, video_id,
183                             'Post by %s' % uploader_id if uploader_id else None,
184                             description)
185
186         if not video_url:
187             video_url = self._og_search_video_url(webpage, secure=False)
188
189         formats = [{
190             'url': video_url,
191             'width': width,
192             'height': height,
193         }]
194
195         if not uploader_id:
196             uploader_id = self._search_regex(
197                 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
198                 webpage, 'uploader id', fatal=False)
199
200         if not description:
201             description = self._search_regex(
202                 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
203             if description is not None:
204                 description = lowercase_escape(description)
205
206         if not thumbnail:
207             thumbnail = self._og_search_thumbnail(webpage)
208
209         return {
210             'id': video_id,
211             'formats': formats,
212             'ext': 'mp4',
213             'title': 'Video by %s' % uploader_id,
214             'description': description,
215             'thumbnail': thumbnail,
216             'timestamp': timestamp,
217             'uploader_id': uploader_id,
218             'uploader': uploader,
219             'like_count': like_count,
220             'comment_count': comment_count,
221             'comments': comments,
222         }
223
224
225 class InstagramUserIE(InfoExtractor):
226     _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
227     IE_DESC = 'Instagram user profile'
228     IE_NAME = 'instagram:user'
229     _TEST = {
230         'url': 'https://instagram.com/porsche',
231         'info_dict': {
232             'id': 'porsche',
233             'title': 'porsche',
234         },
235         'playlist_count': 5,
236         'params': {
237             'extract_flat': True,
238             'skip_download': True,
239             'playlistend': 5,
240         }
241     }
242
243     def _entries(self, data):
244         def get_count(suffix):
245             return int_or_none(try_get(
246                 node, lambda x: x['edge_media_' + suffix]['count']))
247
248         uploader_id = data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
249         csrf_token = data['config']['csrf_token']
250         rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
251
252         self._set_cookie('instagram.com', 'ig_pr', '1')
253
254         cursor = ''
255         for page_num in itertools.count(1):
256             variables = json.dumps({
257                 'id': uploader_id,
258                 'first': 100,
259                 'after': cursor,
260             })
261             s = '%s:%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent'], variables)
262             media = self._download_json(
263                 'https://www.instagram.com/graphql/query/', uploader_id,
264                 'Downloading JSON page %d' % page_num, headers={
265                     'X-Requested-With': 'XMLHttpRequest',
266                     'X-Instagram-GIS': hashlib.md5(s.encode('utf-8')).hexdigest(),
267                 }, query={
268                     'query_hash': '472f257a40c653c64c666ce877d59d2b',
269                     'variables': variables,
270                 })['data']['user']['edge_owner_to_timeline_media']
271
272             edges = media.get('edges')
273             if not edges or not isinstance(edges, list):
274                 break
275
276             for edge in edges:
277                 node = edge.get('node')
278                 if not node or not isinstance(node, dict):
279                     continue
280                 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
281                     continue
282                 video_id = node.get('shortcode')
283                 if not video_id:
284                     continue
285
286                 info = self.url_result(
287                     'https://instagram.com/p/%s/' % video_id,
288                     ie=InstagramIE.ie_key(), video_id=video_id)
289
290                 description = try_get(
291                     node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
292                     compat_str)
293                 thumbnail = node.get('thumbnail_src') or node.get('display_src')
294                 timestamp = int_or_none(node.get('taken_at_timestamp'))
295
296                 comment_count = get_count('to_comment')
297                 like_count = get_count('preview_like')
298                 view_count = int_or_none(node.get('video_view_count'))
299
300                 info.update({
301                     'description': description,
302                     'thumbnail': thumbnail,
303                     'timestamp': timestamp,
304                     'comment_count': comment_count,
305                     'like_count': like_count,
306                     'view_count': view_count,
307                 })
308
309                 yield info
310
311             page_info = media.get('page_info')
312             if not page_info or not isinstance(page_info, dict):
313                 break
314
315             has_next_page = page_info.get('has_next_page')
316             if not has_next_page:
317                 break
318
319             cursor = page_info.get('end_cursor')
320             if not cursor or not isinstance(cursor, compat_str):
321                 break
322
323     def _real_extract(self, url):
324         username = self._match_id(url)
325
326         webpage = self._download_webpage(url, username)
327
328         data = self._parse_json(
329             self._search_regex(
330                 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
331             username)
332
333         return self.playlist_result(
334             self._entries(data), username, username)