You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

381 lines
14 KiB

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