[soundcloud] Prefer HTTP over RTMP (#1798)
[youtube-dl] / youtube_dl / extractor / soundcloud.py
1 import json
2 import re
3 import itertools
4
5 from .common import InfoExtractor
6 from ..utils import (
7     compat_str,
8     compat_urlparse,
9     compat_urllib_parse,
10
11     ExtractorError,
12     unified_strdate,
13 )
14
15
16 class SoundcloudIE(InfoExtractor):
17     """Information extractor for soundcloud.com
18        To access the media, the uid of the song and a stream token
19        must be extracted from the page source and the script must make
20        a request to media.soundcloud.com/crossdomain.xml. Then
21        the media can be grabbed by requesting from an url composed
22        of the stream token and uid
23      """
24
25     _VALID_URL = r'''^(?:https?://)?
26                     (?:(?:(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)/?(?:[?].*)?$)
27                        |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
28                        |(?P<widget>w.soundcloud.com/player/?.*?url=.*)
29                     )
30                     '''
31     IE_NAME = u'soundcloud'
32     _TESTS = [
33         {
34             u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
35             u'file': u'62986583.mp3',
36             u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
37             u'info_dict': {
38                 u"upload_date": u"20121011", 
39                 u"description": u"No Downloads untill we record the finished version this weekend, i was too pumped n i had to post it , earl is prolly gonna b hella p.o'd", 
40                 u"uploader": u"E.T. ExTerrestrial Music", 
41                 u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
42             }
43         },
44         # not streamable song
45         {
46             u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
47             u'info_dict': {
48                 u'id': u'47127627',
49                 u'ext': u'mp3',
50                 u'title': u'Goldrushed',
51                 u'uploader': u'The Royal Concept',
52                 u'upload_date': u'20120521',
53             },
54             u'params': {
55                 # rtmp
56                 u'skip_download': True,
57             },
58         },
59     ]
60
61     _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
62     _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
63
64     @classmethod
65     def suitable(cls, url):
66         return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
67
68     def report_resolve(self, video_id):
69         """Report information extraction."""
70         self.to_screen(u'%s: Resolving id' % video_id)
71
72     @classmethod
73     def _resolv_url(cls, url):
74         return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
75
76     def _extract_info_dict(self, info, full_title=None, quiet=False):
77         track_id = compat_str(info['id'])
78         name = full_title or track_id
79         if quiet:
80             self.report_extraction(name)
81
82         thumbnail = info['artwork_url']
83         if thumbnail is not None:
84             thumbnail = thumbnail.replace('-large', '-t500x500')
85         ext = info.get('original_format', u'mp3')
86         result = {
87             'id': track_id,
88             'uploader': info['user']['username'],
89             'upload_date': unified_strdate(info['created_at']),
90             'title': info['title'],
91             'description': info['description'],
92             'thumbnail': thumbnail,
93         }
94         if info.get('downloadable', False):
95             # We can build a direct link to the song
96             format_url = (
97                 u'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
98                     track_id, self._CLIENT_ID))
99             result['formats'] = [{
100                 'format_id': 'download',
101                 'ext': ext,
102                 'url': format_url,
103             }]
104         else:
105             # We have to retrieve the url
106             stream_json = self._download_webpage(
107                 'http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}'.format(track_id, self._IPHONE_CLIENT_ID),
108                 track_id, u'Downloading track url')
109
110             formats = []
111             format_dict = json.loads(stream_json)
112             for key, stream_url in format_dict.items():
113                 if key.startswith(u'http'):
114                     formats.append({
115                         'format_id': key,
116                         'ext': ext,
117                         'url': stream_url,
118                     })
119                 elif key.startswith(u'rtmp'):
120                     # The url doesn't have an rtmp app, we have to extract the playpath
121                     url, path = stream_url.split('mp3:', 1)
122                     formats.append({
123                         'format_id': key,
124                         'url': url,
125                         'play_path': 'mp3:' + path,
126                         'ext': ext,
127                     })
128
129             if not formats:
130                 # We fallback to the stream_url in the original info, this
131                 # cannot be always used, sometimes it can give an HTTP 404 error
132                 formats.append({
133                     'format_id': u'fallback',
134                     'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
135                     'ext': ext,
136                 })
137
138             def format_pref(f):
139                 if f['format_id'].startswith('http'):
140                     return 2
141                 if f['format_id'].startswith('rtmp'):
142                     return 1
143                 return 0
144
145             formats.sort(key=format_pref)
146             result['formats'] = formats
147
148         return result
149
150     def _real_extract(self, url):
151         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
152         if mobj is None:
153             raise ExtractorError(u'Invalid URL: %s' % url)
154
155         track_id = mobj.group('track_id')
156         if track_id is not None:
157             info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
158             full_title = track_id
159         elif mobj.group('widget'):
160             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
161             return self.url_result(query['url'][0], ie='Soundcloud')
162         else:
163             # extract uploader (which is in the url)
164             uploader = mobj.group(1)
165             # extract simple title (uploader + slug of song title)
166             slug_title =  mobj.group(2)
167             full_title = '%s/%s' % (uploader, slug_title)
168     
169             self.report_resolve(full_title)
170     
171             url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
172             info_json_url = self._resolv_url(url)
173         info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
174
175         info = json.loads(info_json)
176         return self._extract_info_dict(info, full_title)
177
178 class SoundcloudSetIE(SoundcloudIE):
179     _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
180     IE_NAME = u'soundcloud:set'
181     # it's in tests/test_playlists.py
182     _TESTS = []
183
184     def _real_extract(self, url):
185         mobj = re.match(self._VALID_URL, url)
186         if mobj is None:
187             raise ExtractorError(u'Invalid URL: %s' % url)
188
189         # extract uploader (which is in the url)
190         uploader = mobj.group(1)
191         # extract simple title (uploader + slug of song title)
192         slug_title =  mobj.group(2)
193         full_title = '%s/sets/%s' % (uploader, slug_title)
194
195         self.report_resolve(full_title)
196
197         url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
198         resolv_url = self._resolv_url(url)
199         info_json = self._download_webpage(resolv_url, full_title)
200
201         info = json.loads(info_json)
202         if 'errors' in info:
203             for err in info['errors']:
204                 self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
205             return
206
207         self.report_extraction(full_title)
208         return {'_type': 'playlist',
209                 'entries': [self._extract_info_dict(track) for track in info['tracks']],
210                 'id': info['id'],
211                 'title': info['title'],
212                 }
213
214
215 class SoundcloudUserIE(SoundcloudIE):
216     _VALID_URL = r'https?://(www\.)?soundcloud.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
217     IE_NAME = u'soundcloud:user'
218
219     # it's in tests/test_playlists.py
220     _TESTS = []
221
222     def _real_extract(self, url):
223         mobj = re.match(self._VALID_URL, url)
224         uploader = mobj.group('user')
225
226         url = 'http://soundcloud.com/%s/' % uploader
227         resolv_url = self._resolv_url(url)
228         user_json = self._download_webpage(resolv_url, uploader,
229             u'Downloading user info')
230         user = json.loads(user_json)
231
232         tracks = []
233         for i in itertools.count():
234             data = compat_urllib_parse.urlencode({'offset': i*50,
235                                                   'client_id': self._CLIENT_ID,
236                                                   })
237             tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
238             response = self._download_webpage(tracks_url, uploader, 
239                 u'Downloading tracks page %s' % (i+1))
240             new_tracks = json.loads(response)
241             tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
242             if len(new_tracks) < 50:
243                 break
244
245         return {
246             '_type': 'playlist',
247             'id': compat_str(user['id']),
248             'title': user['username'],
249             'entries': tracks,
250         }