mixcloud.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. from __future__ import unicode_literals
  2. import base64
  3. import functools
  4. import itertools
  5. import re
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_chr,
  9. compat_ord,
  10. compat_str,
  11. compat_urllib_parse_unquote,
  12. compat_urlparse,
  13. )
  14. from ..utils import (
  15. clean_html,
  16. ExtractorError,
  17. OnDemandPagedList,
  18. str_to_int,
  19. )
  20. class MixcloudIE(InfoExtractor):
  21. _VALID_URL = r'https?://(?:(?:www|beta|m)\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
  22. IE_NAME = 'mixcloud'
  23. _TESTS = [{
  24. 'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
  25. 'info_dict': {
  26. 'id': 'dholbach-cryptkeeper',
  27. 'ext': 'm4a',
  28. 'title': 'Cryptkeeper',
  29. 'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
  30. 'uploader': 'Daniel Holbach',
  31. 'uploader_id': 'dholbach',
  32. 'thumbnail': r're:https?://.*\.jpg',
  33. 'view_count': int,
  34. },
  35. }, {
  36. 'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
  37. 'info_dict': {
  38. 'id': 'gillespeterson-caribou-7-inch-vinyl-mix-chat',
  39. 'ext': 'mp3',
  40. 'title': 'Caribou 7 inch Vinyl Mix & Chat',
  41. 'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
  42. 'uploader': 'Gilles Peterson Worldwide',
  43. 'uploader_id': 'gillespeterson',
  44. 'thumbnail': 're:https?://.*',
  45. 'view_count': int,
  46. },
  47. }, {
  48. 'url': 'https://beta.mixcloud.com/RedLightRadio/nosedrip-15-red-light-radio-01-18-2016/',
  49. 'only_matching': True,
  50. }]
  51. _keys = [
  52. 'return { requestAnimationFrame: function(callback) { callback(); }, innerHeight: 500 };',
  53. 'pleasedontdownloadourmusictheartistswontgetpaid',
  54. 'window.addEventListener = window.addEventListener || function() {};',
  55. '(function() { return new Date().toLocaleDateString(); })()'
  56. ]
  57. _current_key = None
  58. # See https://www.mixcloud.com/media/js2/www_js_2.9e23256562c080482435196ca3975ab5.js
  59. def _decrypt_play_info(self, play_info, video_id):
  60. play_info = base64.b64decode(play_info.encode('ascii'))
  61. for num, key in enumerate(self._keys, start=1):
  62. try:
  63. return self._parse_json(
  64. ''.join([
  65. compat_chr(compat_ord(ch) ^ compat_ord(key[idx % len(key)]))
  66. for idx, ch in enumerate(play_info)]),
  67. video_id)
  68. except ExtractorError:
  69. if num == len(self._keys):
  70. raise
  71. def _real_extract(self, url):
  72. mobj = re.match(self._VALID_URL, url)
  73. uploader = mobj.group(1)
  74. cloudcast_name = mobj.group(2)
  75. track_id = compat_urllib_parse_unquote('-'.join((uploader, cloudcast_name)))
  76. webpage = self._download_webpage(url, track_id)
  77. if not self._current_key:
  78. js_url = self._search_regex(
  79. r'<script[^>]+\bsrc=["\"](https://(?:www\.)?mixcloud\.com/media/js2/www_js_4\.[^>]+\.js)',
  80. webpage, 'js url', default=None)
  81. if js_url:
  82. js = self._download_webpage(js_url, track_id, fatal=False)
  83. if js:
  84. key = self._search_regex(
  85. r'player\s*:\s*{.*?\bvalue\s*:\s*(["\'])(?P<key>(?:(?!\1).)+)\1',
  86. js, 'key', default=None, group='key')
  87. if key and isinstance(key, compat_str):
  88. self._keys.insert(0, key)
  89. self._current_key = key
  90. message = self._html_search_regex(
  91. r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
  92. webpage, 'error message', default=None)
  93. encrypted_play_info = self._search_regex(
  94. r'm-play-info="([^"]+)"', webpage, 'play info')
  95. play_info = self._decrypt_play_info(encrypted_play_info, track_id)
  96. if message and 'stream_url' not in play_info:
  97. raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
  98. song_url = play_info['stream_url']
  99. title = self._html_search_regex(r'm-title="([^"]+)"', webpage, 'title')
  100. thumbnail = self._proto_relative_url(self._html_search_regex(
  101. r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail', fatal=False))
  102. uploader = self._html_search_regex(
  103. r'm-owner-name="([^"]+)"', webpage, 'uploader', fatal=False)
  104. uploader_id = self._search_regex(
  105. r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
  106. description = self._og_search_description(webpage)
  107. view_count = str_to_int(self._search_regex(
  108. [r'<meta itemprop="interactionCount" content="UserPlays:([0-9]+)"',
  109. r'/listeners/?">([0-9,.]+)</a>',
  110. r'(?:m|data)-tooltip=["\']([\d,.]+) plays'],
  111. webpage, 'play count', default=None))
  112. return {
  113. 'id': track_id,
  114. 'title': title,
  115. 'url': song_url,
  116. 'description': description,
  117. 'thumbnail': thumbnail,
  118. 'uploader': uploader,
  119. 'uploader_id': uploader_id,
  120. 'view_count': view_count,
  121. }
  122. class MixcloudPlaylistBaseIE(InfoExtractor):
  123. _PAGE_SIZE = 24
  124. def _find_urls_in_page(self, page):
  125. for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', page):
  126. yield self.url_result(
  127. compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
  128. MixcloudIE.ie_key())
  129. def _fetch_tracks_page(self, path, video_id, page_name, current_page, real_page_number=None):
  130. real_page_number = real_page_number or current_page + 1
  131. return self._download_webpage(
  132. 'https://www.mixcloud.com/%s/' % path, video_id,
  133. note='Download %s (page %d)' % (page_name, current_page + 1),
  134. errnote='Unable to download %s' % page_name,
  135. query={'page': real_page_number, 'list': 'main', '_ajax': '1'},
  136. headers={'X-Requested-With': 'XMLHttpRequest'})
  137. def _tracks_page_func(self, page, video_id, page_name, current_page):
  138. resp = self._fetch_tracks_page(page, video_id, page_name, current_page)
  139. for item in self._find_urls_in_page(resp):
  140. yield item
  141. def _get_user_description(self, page_content):
  142. return self._html_search_regex(
  143. r'<div[^>]+class="profile-bio"[^>]*>(.+?)</div>',
  144. page_content, 'user description', fatal=False)
  145. class MixcloudUserIE(MixcloudPlaylistBaseIE):
  146. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
  147. IE_NAME = 'mixcloud:user'
  148. _TESTS = [{
  149. 'url': 'http://www.mixcloud.com/dholbach/',
  150. 'info_dict': {
  151. 'id': 'dholbach_uploads',
  152. 'title': 'Daniel Holbach (uploads)',
  153. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  154. },
  155. 'playlist_mincount': 11,
  156. }, {
  157. 'url': 'http://www.mixcloud.com/dholbach/uploads/',
  158. 'info_dict': {
  159. 'id': 'dholbach_uploads',
  160. 'title': 'Daniel Holbach (uploads)',
  161. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  162. },
  163. 'playlist_mincount': 11,
  164. }, {
  165. 'url': 'http://www.mixcloud.com/dholbach/favorites/',
  166. 'info_dict': {
  167. 'id': 'dholbach_favorites',
  168. 'title': 'Daniel Holbach (favorites)',
  169. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  170. },
  171. 'params': {
  172. 'playlist_items': '1-100',
  173. },
  174. 'playlist_mincount': 100,
  175. }, {
  176. 'url': 'http://www.mixcloud.com/dholbach/listens/',
  177. 'info_dict': {
  178. 'id': 'dholbach_listens',
  179. 'title': 'Daniel Holbach (listens)',
  180. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  181. },
  182. 'params': {
  183. 'playlist_items': '1-100',
  184. },
  185. 'playlist_mincount': 100,
  186. }]
  187. def _real_extract(self, url):
  188. mobj = re.match(self._VALID_URL, url)
  189. user_id = mobj.group('user')
  190. list_type = mobj.group('type')
  191. # if only a profile URL was supplied, default to download all uploads
  192. if list_type is None:
  193. list_type = 'uploads'
  194. video_id = '%s_%s' % (user_id, list_type)
  195. profile = self._download_webpage(
  196. 'https://www.mixcloud.com/%s/' % user_id, video_id,
  197. note='Downloading user profile',
  198. errnote='Unable to download user profile')
  199. username = self._og_search_title(profile)
  200. description = self._get_user_description(profile)
  201. entries = OnDemandPagedList(
  202. functools.partial(
  203. self._tracks_page_func,
  204. '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
  205. self._PAGE_SIZE, use_cache=True)
  206. return self.playlist_result(
  207. entries, video_id, '%s (%s)' % (username, list_type), description)
  208. class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
  209. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
  210. IE_NAME = 'mixcloud:playlist'
  211. _TESTS = [{
  212. 'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
  213. 'info_dict': {
  214. 'id': 'RedBullThre3style_tokyo-finalists-2015',
  215. 'title': 'National Champions 2015',
  216. 'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
  217. },
  218. 'playlist_mincount': 16,
  219. }, {
  220. 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
  221. 'only_matching': True,
  222. }]
  223. def _real_extract(self, url):
  224. mobj = re.match(self._VALID_URL, url)
  225. user_id = mobj.group('user')
  226. playlist_id = mobj.group('playlist')
  227. video_id = '%s_%s' % (user_id, playlist_id)
  228. webpage = self._download_webpage(
  229. url, user_id,
  230. note='Downloading playlist page',
  231. errnote='Unable to download playlist page')
  232. title = self._html_search_regex(
  233. r'<a[^>]+class="parent active"[^>]*><b>\d+</b><span[^>]*>([^<]+)',
  234. webpage, 'playlist title',
  235. default=None) or self._og_search_title(webpage, fatal=False)
  236. description = self._get_user_description(webpage)
  237. entries = OnDemandPagedList(
  238. functools.partial(
  239. self._tracks_page_func,
  240. '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
  241. self._PAGE_SIZE)
  242. return self.playlist_result(entries, video_id, title, description)
  243. class MixcloudStreamIE(MixcloudPlaylistBaseIE):
  244. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/stream/?$'
  245. IE_NAME = 'mixcloud:stream'
  246. _TEST = {
  247. 'url': 'https://www.mixcloud.com/FirstEar/stream/',
  248. 'info_dict': {
  249. 'id': 'FirstEar',
  250. 'title': 'First Ear',
  251. 'description': 'Curators of good music\nfirstearmusic.com',
  252. },
  253. 'playlist_mincount': 192,
  254. }
  255. def _real_extract(self, url):
  256. user_id = self._match_id(url)
  257. webpage = self._download_webpage(url, user_id)
  258. entries = []
  259. prev_page_url = None
  260. def _handle_page(page):
  261. entries.extend(self._find_urls_in_page(page))
  262. return self._search_regex(
  263. r'm-next-page-url="([^"]+)"', page,
  264. 'next page URL', default=None)
  265. next_page_url = _handle_page(webpage)
  266. for idx in itertools.count(0):
  267. if not next_page_url or prev_page_url == next_page_url:
  268. break
  269. prev_page_url = next_page_url
  270. current_page = int(self._search_regex(
  271. r'\?page=(\d+)', next_page_url, 'next page number'))
  272. next_page_url = _handle_page(self._fetch_tracks_page(
  273. '%s/stream' % user_id, user_id, 'stream', idx,
  274. real_page_number=current_page))
  275. username = self._og_search_title(webpage)
  276. description = self._get_user_description(webpage)
  277. return self.playlist_result(entries, user_id, username, description)