[instagram] Add support for embed URLs
[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 )
12
13
14 class InstagramIE(InfoExtractor):
15     _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/p/(?P<id>[^/?#&]+))'
16     _TESTS = [{
17         'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
18         'md5': '0d2da106a9d2631273e192b372806516',
19         'info_dict': {
20             'id': 'aye83DjauH',
21             'ext': 'mp4',
22             'uploader_id': 'naomipq',
23             'title': 'Video by naomipq',
24             'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
25         }
26     }, {
27         # missing description
28         'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
29         'info_dict': {
30             'id': 'BA-pQFBG8HZ',
31             'ext': 'mp4',
32             'uploader_id': 'britneyspears',
33             'title': 'Video by britneyspears',
34         },
35         'params': {
36             'skip_download': True,
37         },
38     }, {
39         'url': 'https://instagram.com/p/-Cmh1cukG2/',
40         'only_matching': True,
41     }, {
42         'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
43         'only_matching': True,
44     }]
45
46     @staticmethod
47     def _extract_embed_url(webpage):
48         blockquote_el = get_element_by_attribute(
49             'class', 'instagram-media', webpage)
50         if blockquote_el is None:
51             return
52
53         mobj = re.search(
54             r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
55         if mobj:
56             return mobj.group('link')
57
58     def _real_extract(self, url):
59         mobj = re.match(self._VALID_URL, url)
60         video_id = mobj.group('id')
61         url = mobj.group('url')
62
63         webpage = self._download_webpage(url, video_id)
64         uploader_id = self._search_regex(r'"owner":{"username":"(.+?)"',
65                                          webpage, 'uploader id', fatal=False)
66         desc = self._search_regex(
67             r'"caption":"(.+?)"', webpage, 'description', default=None)
68         if desc is not None:
69             desc = lowercase_escape(desc)
70
71         return {
72             'id': video_id,
73             'url': self._og_search_video_url(webpage, secure=False),
74             'ext': 'mp4',
75             'title': 'Video by %s' % uploader_id,
76             'thumbnail': self._og_search_thumbnail(webpage),
77             'uploader_id': uploader_id,
78             'description': desc,
79         }
80
81
82 class InstagramUserIE(InfoExtractor):
83     _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<username>[^/]{2,})/?(?:$|[?#])'
84     IE_DESC = 'Instagram user profile'
85     IE_NAME = 'instagram:user'
86     _TEST = {
87         'url': 'https://instagram.com/porsche',
88         'info_dict': {
89             'id': 'porsche',
90             'title': 'porsche',
91         },
92         'playlist_mincount': 2,
93         'playlist': [{
94             'info_dict': {
95                 'id': '614605558512799803_462752227',
96                 'ext': 'mp4',
97                 'title': '#Porsche Intelligent Performance.',
98                 'thumbnail': 're:^https?://.*\.jpg',
99                 'uploader': 'Porsche',
100                 'uploader_id': 'porsche',
101                 'timestamp': 1387486713,
102                 'upload_date': '20131219',
103             },
104         }],
105         'params': {
106             'extract_flat': True,
107             'skip_download': True,
108         }
109     }
110
111     def _real_extract(self, url):
112         mobj = re.match(self._VALID_URL, url)
113         uploader_id = mobj.group('username')
114
115         entries = []
116         page_count = 0
117         media_url = 'http://instagram.com/%s/media' % uploader_id
118         while True:
119             page = self._download_json(
120                 media_url, uploader_id,
121                 note='Downloading page %d ' % (page_count + 1),
122             )
123             page_count += 1
124
125             for it in page['items']:
126                 if it.get('type') != 'video':
127                     continue
128                 like_count = int_or_none(it.get('likes', {}).get('count'))
129                 user = it.get('user', {})
130
131                 formats = [{
132                     'format_id': k,
133                     'height': v.get('height'),
134                     'width': v.get('width'),
135                     'url': v['url'],
136                 } for k, v in it['videos'].items()]
137                 self._sort_formats(formats)
138
139                 thumbnails_el = it.get('images', {})
140                 thumbnail = thumbnails_el.get('thumbnail', {}).get('url')
141
142                 # In some cases caption is null, which corresponds to None
143                 # in python. As a result, it.get('caption', {}) gives None
144                 title = (it.get('caption') or {}).get('text', it['id'])
145
146                 entries.append({
147                     'id': it['id'],
148                     'title': limit_length(title, 80),
149                     'formats': formats,
150                     'thumbnail': thumbnail,
151                     'webpage_url': it.get('link'),
152                     'uploader': user.get('full_name'),
153                     'uploader_id': user.get('username'),
154                     'like_count': like_count,
155                     'timestamp': int_or_none(it.get('created_time')),
156                 })
157
158             if not page['items']:
159                 break
160             max_id = page['items'][-1]['id'].split('_')[0]
161             media_url = (
162                 'http://instagram.com/%s/media?max_id=%s' % (
163                     uploader_id, max_id))
164
165         return {
166             '_type': 'playlist',
167             'entries': entries,
168             'id': uploader_id,
169             'title': uploader_id,
170         }