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