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