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