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