[Instagram] Extract comments
[youtube-dl] / youtube_dl / extractor / instagram.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..utils import (
7     get_element_by_attribute,
8     int_or_none,
9     limit_length,
10     lowercase_escape,
11     try_get,
12 )
13
14
15 class InstagramIE(InfoExtractor):
16     _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/p/(?P<id>[^/?#&]+))'
17     _TESTS = [{
18         'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
19         'md5': '0d2da106a9d2631273e192b372806516',
20         'info_dict': {
21             'id': 'aye83DjauH',
22             'ext': 'mp4',
23             'title': 'Video by naomipq',
24             'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
25             'thumbnail': 're:^https?://.*\.jpg',
26             'timestamp': 1371748545,
27             'upload_date': '20130620',
28             'uploader_id': 'naomipq',
29             'uploader': 'Naomi Leonor Phan-Quang',
30             'like_count': int,
31             'comment_count': int,
32             'comments': list,
33         },
34     }, {
35         # missing description
36         'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
37         'info_dict': {
38             'id': 'BA-pQFBG8HZ',
39             'ext': 'mp4',
40             'title': 'Video by britneyspears',
41             'thumbnail': 're:^https?://.*\.jpg',
42             'timestamp': 1453760977,
43             'upload_date': '20160125',
44             'uploader_id': 'britneyspears',
45             'uploader': 'Britney Spears',
46             'like_count': int,
47             'comment_count': int,
48             'comments': list,
49         },
50         'params': {
51             'skip_download': True,
52         },
53     }, {
54         'url': 'https://instagram.com/p/-Cmh1cukG2/',
55         'only_matching': True,
56     }, {
57         'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
58         'only_matching': True,
59     }]
60
61     @staticmethod
62     def _extract_embed_url(webpage):
63         mobj = re.search(
64             r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
65             webpage)
66         if mobj:
67             return mobj.group('url')
68
69         blockquote_el = get_element_by_attribute(
70             'class', 'instagram-media', webpage)
71         if blockquote_el is None:
72             return
73
74         mobj = re.search(
75             r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
76         if mobj:
77             return mobj.group('link')
78
79     def _real_extract(self, url):
80         mobj = re.match(self._VALID_URL, url)
81         video_id = mobj.group('id')
82         url = mobj.group('url')
83
84         webpage = self._download_webpage(url, video_id)
85
86         (video_url, description, thumbnail, timestamp, uploader,
87          uploader_id, like_count, comment_count) = [None] * 8
88
89         shared_data = self._parse_json(
90             self._search_regex(
91                 r'window\._sharedData\s*=\s*({.+?});',
92                 webpage, 'shared data', default='{}'),
93             video_id, fatal=False)
94         if shared_data:
95             media = try_get(
96                 shared_data, lambda x: x['entry_data']['PostPage'][0]['media'], dict)
97             if media:
98                 video_url = media.get('video_url')
99                 description = media.get('caption')
100                 thumbnail = media.get('display_src')
101                 timestamp = int_or_none(media.get('date'))
102                 uploader = media.get('owner', {}).get('full_name')
103                 uploader_id = media.get('owner', {}).get('username')
104                 like_count = int_or_none(media.get('likes', {}).get('count'))
105                 comment_count = int_or_none(media.get('comments', {}).get('count'))
106                 comments = [{
107                     'author': comment.get('user', {}).get('username'),
108                     'author_id': comment.get('user', {}).get('id'),
109                     'id': comment.get('id'),
110                     'text': comment.get('text'),
111                     'timestamp': int_or_none(comment.get('created_at')),
112                 } for comment in media.get('comments', {}).get('nodes', [])
113                 if comment.get('text')]
114
115         if not video_url:
116             video_url = self._og_search_video_url(webpage, secure=False)
117
118         if not uploader_id:
119             uploader_id = self._search_regex(
120                 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
121                 webpage, 'uploader id', fatal=False)
122
123         if not description:
124             description = self._search_regex(
125                 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
126             if description is not None:
127                 description = lowercase_escape(description)
128
129         if not thumbnail:
130             thumbnail = self._og_search_thumbnail(webpage)
131
132         return {
133             'id': video_id,
134             'url': video_url,
135             'ext': 'mp4',
136             'title': 'Video by %s' % uploader_id,
137             'description': description,
138             'thumbnail': thumbnail,
139             'timestamp': timestamp,
140             'uploader_id': uploader_id,
141             'uploader': uploader,
142             'like_count': like_count,
143             'comment_count': comment_count,
144             'comments': comments,
145         }
146
147
148 class InstagramUserIE(InfoExtractor):
149     _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<username>[^/]{2,})/?(?:$|[?#])'
150     IE_DESC = 'Instagram user profile'
151     IE_NAME = 'instagram:user'
152     _TEST = {
153         'url': 'https://instagram.com/porsche',
154         'info_dict': {
155             'id': 'porsche',
156             'title': 'porsche',
157         },
158         'playlist_mincount': 2,
159         'playlist': [{
160             'info_dict': {
161                 'id': '614605558512799803_462752227',
162                 'ext': 'mp4',
163                 'title': '#Porsche Intelligent Performance.',
164                 'thumbnail': 're:^https?://.*\.jpg',
165                 'uploader': 'Porsche',
166                 'uploader_id': 'porsche',
167                 'timestamp': 1387486713,
168                 'upload_date': '20131219',
169             },
170         }],
171         'params': {
172             'extract_flat': True,
173             'skip_download': True,
174         }
175     }
176
177     def _real_extract(self, url):
178         mobj = re.match(self._VALID_URL, url)
179         uploader_id = mobj.group('username')
180
181         entries = []
182         page_count = 0
183         media_url = 'http://instagram.com/%s/media' % uploader_id
184         while True:
185             page = self._download_json(
186                 media_url, uploader_id,
187                 note='Downloading page %d ' % (page_count + 1),
188             )
189             page_count += 1
190
191             for it in page['items']:
192                 if it.get('type') != 'video':
193                     continue
194                 like_count = int_or_none(it.get('likes', {}).get('count'))
195                 user = it.get('user', {})
196
197                 formats = [{
198                     'format_id': k,
199                     'height': v.get('height'),
200                     'width': v.get('width'),
201                     'url': v['url'],
202                 } for k, v in it['videos'].items()]
203                 self._sort_formats(formats)
204
205                 thumbnails_el = it.get('images', {})
206                 thumbnail = thumbnails_el.get('thumbnail', {}).get('url')
207
208                 # In some cases caption is null, which corresponds to None
209                 # in python. As a result, it.get('caption', {}) gives None
210                 title = (it.get('caption') or {}).get('text', it['id'])
211
212                 entries.append({
213                     'id': it['id'],
214                     'title': limit_length(title, 80),
215                     'formats': formats,
216                     'thumbnail': thumbnail,
217                     'webpage_url': it.get('link'),
218                     'uploader': user.get('full_name'),
219                     'uploader_id': user.get('username'),
220                     'like_count': like_count,
221                     'timestamp': int_or_none(it.get('created_time')),
222                 })
223
224             if not page['items']:
225                 break
226             max_id = page['items'][-1]['id'].split('_')[0]
227             media_url = (
228                 'http://instagram.com/%s/media?max_id=%s' % (
229                     uploader_id, max_id))
230
231         return {
232             '_type': 'playlist',
233             'entries': entries,
234             'id': uploader_id,
235             'title': uploader_id,
236         }