Merge remote-tracking branch 'jaimeMF/yt-playlists'
[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 == False:
80             self.report_extraction(name)
81
82         thumbnail = info['artwork_url']
83         if thumbnail is not None:
84             thumbnail = thumbnail.replace('-large', '-t500x500')
85         result = {
86             'id':       track_id,
87             'uploader': info['user']['username'],
88             'upload_date': unified_strdate(info['created_at']),
89             'title':    info['title'],
90             'ext':      info.get('original_format', u'mp3'),
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             result['url'] = 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(track_id, self._CLIENT_ID)
97         else:
98             # We have to retrieve the url
99             stream_json = self._download_webpage(
100                 'http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}'.format(track_id, self._IPHONE_CLIENT_ID),
101                 track_id, u'Downloading track url')
102             # There should be only one entry in the dictionary
103             key, stream_url = list(json.loads(stream_json).items())[0]
104             if key.startswith(u'http'):
105                 result['url'] = stream_url
106             elif key.startswith(u'rtmp'):
107                 # The url doesn't have an rtmp app, we have to extract the playpath
108                 url, path = stream_url.split('mp3:', 1)
109                 result.update({
110                     'url': url,
111                     'play_path': 'mp3:' + path,
112                 })
113             else:
114                 # We fallback to the stream_url in the original info, this
115                 # cannot be always used, sometimes it can give an HTTP 404 error
116                 result['url'] = info['stream_url'] + '?client_id=' + self._CLIENT_ID,
117
118         return result
119
120     def _real_extract(self, url):
121         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
122         if mobj is None:
123             raise ExtractorError(u'Invalid URL: %s' % url)
124
125         track_id = mobj.group('track_id')
126         if track_id is not None:
127             info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
128             full_title = track_id
129         elif mobj.group('widget'):
130             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
131             return self.url_result(query['url'][0], ie='Soundcloud')
132         else:
133             # extract uploader (which is in the url)
134             uploader = mobj.group(1)
135             # extract simple title (uploader + slug of song title)
136             slug_title =  mobj.group(2)
137             full_title = '%s/%s' % (uploader, slug_title)
138     
139             self.report_resolve(full_title)
140     
141             url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
142             info_json_url = self._resolv_url(url)
143         info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
144
145         info = json.loads(info_json)
146         return self._extract_info_dict(info, full_title)
147
148 class SoundcloudSetIE(SoundcloudIE):
149     _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
150     IE_NAME = u'soundcloud:set'
151     # it's in tests/test_playlists.py
152     _TESTS = []
153
154     def _real_extract(self, url):
155         mobj = re.match(self._VALID_URL, url)
156         if mobj is None:
157             raise ExtractorError(u'Invalid URL: %s' % url)
158
159         # extract uploader (which is in the url)
160         uploader = mobj.group(1)
161         # extract simple title (uploader + slug of song title)
162         slug_title =  mobj.group(2)
163         full_title = '%s/sets/%s' % (uploader, slug_title)
164
165         self.report_resolve(full_title)
166
167         url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
168         resolv_url = self._resolv_url(url)
169         info_json = self._download_webpage(resolv_url, full_title)
170
171         info = json.loads(info_json)
172         if 'errors' in info:
173             for err in info['errors']:
174                 self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
175             return
176
177         self.report_extraction(full_title)
178         return {'_type': 'playlist',
179                 'entries': [self._extract_info_dict(track) for track in info['tracks']],
180                 'id': info['id'],
181                 'title': info['title'],
182                 }
183
184
185 class SoundcloudUserIE(SoundcloudIE):
186     _VALID_URL = r'https?://(www\.)?soundcloud.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
187     IE_NAME = u'soundcloud:user'
188
189     # it's in tests/test_playlists.py
190     _TESTS = []
191
192     def _real_extract(self, url):
193         mobj = re.match(self._VALID_URL, url)
194         uploader = mobj.group('user')
195
196         url = 'http://soundcloud.com/%s/' % uploader
197         resolv_url = self._resolv_url(url)
198         user_json = self._download_webpage(resolv_url, uploader,
199             u'Downloading user info')
200         user = json.loads(user_json)
201
202         tracks = []
203         for i in itertools.count():
204             data = compat_urllib_parse.urlencode({'offset': i*50,
205                                                   'client_id': self._CLIENT_ID,
206                                                   })
207             tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
208             response = self._download_webpage(tracks_url, uploader, 
209                 u'Downloading tracks page %s' % (i+1))
210             new_tracks = json.loads(response)
211             tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
212             if len(new_tracks) < 50:
213                 break
214
215         return {
216             '_type': 'playlist',
217             'id': compat_str(user['id']),
218             'title': user['username'],
219             'entries': tracks,
220         }