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