soundcloud.py 13 KB

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