mixcloud.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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_RE_TEMPLATE = r'player\s*:\s*{.*?\b%s\s*:\s*(["\'])(?P<key>(?:(?!\1).)+)\1'
  85. for key_name in ('value', 'key_value'):
  86. key = self._search_regex(
  87. KEY_RE_TEMPLATE % key_name, js, 'key',
  88. default=None, group='key')
  89. if key and isinstance(key, compat_str):
  90. self._keys.insert(0, key)
  91. self._current_key = key
  92. message = self._html_search_regex(
  93. r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
  94. webpage, 'error message', default=None)
  95. encrypted_play_info = self._search_regex(
  96. r'm-play-info="([^"]+)"', webpage, 'play info')
  97. play_info = self._decrypt_play_info(encrypted_play_info, track_id)
  98. if message and 'stream_url' not in play_info:
  99. raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
  100. song_url = play_info['stream_url']
  101. title = self._html_search_regex(r'm-title="([^"]+)"', webpage, 'title')
  102. thumbnail = self._proto_relative_url(self._html_search_regex(
  103. r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail', fatal=False))
  104. uploader = self._html_search_regex(
  105. r'm-owner-name="([^"]+)"', webpage, 'uploader', fatal=False)
  106. uploader_id = self._search_regex(
  107. r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
  108. description = self._og_search_description(webpage)
  109. view_count = str_to_int(self._search_regex(
  110. [r'<meta itemprop="interactionCount" content="UserPlays:([0-9]+)"',
  111. r'/listeners/?">([0-9,.]+)</a>',
  112. r'(?:m|data)-tooltip=["\']([\d,.]+) plays'],
  113. webpage, 'play count', default=None))
  114. return {
  115. 'id': track_id,
  116. 'title': title,
  117. 'url': song_url,
  118. 'description': description,
  119. 'thumbnail': thumbnail,
  120. 'uploader': uploader,
  121. 'uploader_id': uploader_id,
  122. 'view_count': view_count,
  123. }
  124. class MixcloudPlaylistBaseIE(InfoExtractor):
  125. _PAGE_SIZE = 24
  126. def _find_urls_in_page(self, page):
  127. for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', page):
  128. yield self.url_result(
  129. compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
  130. MixcloudIE.ie_key())
  131. def _fetch_tracks_page(self, path, video_id, page_name, current_page, real_page_number=None):
  132. real_page_number = real_page_number or current_page + 1
  133. return self._download_webpage(
  134. 'https://www.mixcloud.com/%s/' % path, video_id,
  135. note='Download %s (page %d)' % (page_name, current_page + 1),
  136. errnote='Unable to download %s' % page_name,
  137. query={'page': real_page_number, 'list': 'main', '_ajax': '1'},
  138. headers={'X-Requested-With': 'XMLHttpRequest'})
  139. def _tracks_page_func(self, page, video_id, page_name, current_page):
  140. resp = self._fetch_tracks_page(page, video_id, page_name, current_page)
  141. for item in self._find_urls_in_page(resp):
  142. yield item
  143. def _get_user_description(self, page_content):
  144. return self._html_search_regex(
  145. r'<div[^>]+class="profile-bio"[^>]*>(.+?)</div>',
  146. page_content, 'user description', fatal=False)
  147. class MixcloudUserIE(MixcloudPlaylistBaseIE):
  148. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
  149. IE_NAME = 'mixcloud:user'
  150. _TESTS = [{
  151. 'url': 'http://www.mixcloud.com/dholbach/',
  152. 'info_dict': {
  153. 'id': 'dholbach_uploads',
  154. 'title': 'Daniel Holbach (uploads)',
  155. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  156. },
  157. 'playlist_mincount': 11,
  158. }, {
  159. 'url': 'http://www.mixcloud.com/dholbach/uploads/',
  160. 'info_dict': {
  161. 'id': 'dholbach_uploads',
  162. 'title': 'Daniel Holbach (uploads)',
  163. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  164. },
  165. 'playlist_mincount': 11,
  166. }, {
  167. 'url': 'http://www.mixcloud.com/dholbach/favorites/',
  168. 'info_dict': {
  169. 'id': 'dholbach_favorites',
  170. 'title': 'Daniel Holbach (favorites)',
  171. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  172. },
  173. 'params': {
  174. 'playlist_items': '1-100',
  175. },
  176. 'playlist_mincount': 100,
  177. }, {
  178. 'url': 'http://www.mixcloud.com/dholbach/listens/',
  179. 'info_dict': {
  180. 'id': 'dholbach_listens',
  181. 'title': 'Daniel Holbach (listens)',
  182. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  183. },
  184. 'params': {
  185. 'playlist_items': '1-100',
  186. },
  187. 'playlist_mincount': 100,
  188. }]
  189. def _real_extract(self, url):
  190. mobj = re.match(self._VALID_URL, url)
  191. user_id = mobj.group('user')
  192. list_type = mobj.group('type')
  193. # if only a profile URL was supplied, default to download all uploads
  194. if list_type is None:
  195. list_type = 'uploads'
  196. video_id = '%s_%s' % (user_id, list_type)
  197. profile = self._download_webpage(
  198. 'https://www.mixcloud.com/%s/' % user_id, video_id,
  199. note='Downloading user profile',
  200. errnote='Unable to download user profile')
  201. username = self._og_search_title(profile)
  202. description = self._get_user_description(profile)
  203. entries = OnDemandPagedList(
  204. functools.partial(
  205. self._tracks_page_func,
  206. '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
  207. self._PAGE_SIZE, use_cache=True)
  208. return self.playlist_result(
  209. entries, video_id, '%s (%s)' % (username, list_type), description)
  210. class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
  211. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
  212. IE_NAME = 'mixcloud:playlist'
  213. _TESTS = [{
  214. 'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
  215. 'info_dict': {
  216. 'id': 'RedBullThre3style_tokyo-finalists-2015',
  217. 'title': 'National Champions 2015',
  218. 'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
  219. },
  220. 'playlist_mincount': 16,
  221. }, {
  222. 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
  223. 'only_matching': True,
  224. }]
  225. def _real_extract(self, url):
  226. mobj = re.match(self._VALID_URL, url)
  227. user_id = mobj.group('user')
  228. playlist_id = mobj.group('playlist')
  229. video_id = '%s_%s' % (user_id, playlist_id)
  230. webpage = self._download_webpage(
  231. url, user_id,
  232. note='Downloading playlist page',
  233. errnote='Unable to download playlist page')
  234. title = self._html_search_regex(
  235. r'<a[^>]+class="parent active"[^>]*><b>\d+</b><span[^>]*>([^<]+)',
  236. webpage, 'playlist title',
  237. default=None) or self._og_search_title(webpage, fatal=False)
  238. description = self._get_user_description(webpage)
  239. entries = OnDemandPagedList(
  240. functools.partial(
  241. self._tracks_page_func,
  242. '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
  243. self._PAGE_SIZE)
  244. return self.playlist_result(entries, video_id, title, description)
  245. class MixcloudStreamIE(MixcloudPlaylistBaseIE):
  246. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/stream/?$'
  247. IE_NAME = 'mixcloud:stream'
  248. _TEST = {
  249. 'url': 'https://www.mixcloud.com/FirstEar/stream/',
  250. 'info_dict': {
  251. 'id': 'FirstEar',
  252. 'title': 'First Ear',
  253. 'description': 'Curators of good music\nfirstearmusic.com',
  254. },
  255. 'playlist_mincount': 192,
  256. }
  257. def _real_extract(self, url):
  258. user_id = self._match_id(url)
  259. webpage = self._download_webpage(url, user_id)
  260. entries = []
  261. prev_page_url = None
  262. def _handle_page(page):
  263. entries.extend(self._find_urls_in_page(page))
  264. return self._search_regex(
  265. r'm-next-page-url="([^"]+)"', page,
  266. 'next page URL', default=None)
  267. next_page_url = _handle_page(webpage)
  268. for idx in itertools.count(0):
  269. if not next_page_url or prev_page_url == next_page_url:
  270. break
  271. prev_page_url = next_page_url
  272. current_page = int(self._search_regex(
  273. r'\?page=(\d+)', next_page_url, 'next page number'))
  274. next_page_url = _handle_page(self._fetch_tracks_page(
  275. '%s/stream' % user_id, user_id, 'stream', idx,
  276. real_page_number=current_page))
  277. username = self._og_search_title(webpage)
  278. description = self._get_user_description(webpage)
  279. return self.playlist_result(entries, user_id, username, description)