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