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