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