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