mixcloud.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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_b64decode,
  9. compat_chr,
  10. compat_ord,
  11. compat_str,
  12. compat_urllib_parse_unquote,
  13. compat_urlparse,
  14. compat_zip
  15. )
  16. from ..utils import (
  17. clean_html,
  18. ExtractorError,
  19. int_or_none,
  20. OnDemandPagedList,
  21. str_to_int,
  22. try_get,
  23. urljoin,
  24. )
  25. class MixcloudIE(InfoExtractor):
  26. _VALID_URL = r'https?://(?:(?:www|beta|m)\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
  27. IE_NAME = 'mixcloud'
  28. _TESTS = [{
  29. 'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
  30. 'info_dict': {
  31. 'id': 'dholbach-cryptkeeper',
  32. 'ext': 'm4a',
  33. 'title': 'Cryptkeeper',
  34. 'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
  35. 'uploader': 'Daniel Holbach',
  36. 'uploader_id': 'dholbach',
  37. 'thumbnail': r're:https?://.*\.jpg',
  38. 'view_count': int,
  39. },
  40. }, {
  41. 'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
  42. 'info_dict': {
  43. 'id': 'gillespeterson-caribou-7-inch-vinyl-mix-chat',
  44. 'ext': 'mp3',
  45. 'title': 'Caribou 7 inch Vinyl Mix & Chat',
  46. 'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
  47. 'uploader': 'Gilles Peterson Worldwide',
  48. 'uploader_id': 'gillespeterson',
  49. 'thumbnail': 're:https?://.*',
  50. 'view_count': int,
  51. },
  52. }, {
  53. 'url': 'https://beta.mixcloud.com/RedLightRadio/nosedrip-15-red-light-radio-01-18-2016/',
  54. 'only_matching': True,
  55. }]
  56. @staticmethod
  57. def _decrypt_xor_cipher(key, ciphertext):
  58. """Encrypt/Decrypt XOR cipher. Both ways are possible because it's XOR."""
  59. return ''.join([
  60. compat_chr(compat_ord(ch) ^ compat_ord(k))
  61. for ch, k in compat_zip(ciphertext, itertools.cycle(key))])
  62. def _real_extract(self, url):
  63. mobj = re.match(self._VALID_URL, url)
  64. uploader = mobj.group(1)
  65. cloudcast_name = mobj.group(2)
  66. track_id = compat_urllib_parse_unquote('-'.join((uploader, cloudcast_name)))
  67. webpage = self._download_webpage(url, track_id)
  68. # Legacy path
  69. encrypted_play_info = self._search_regex(
  70. r'm-play-info="([^"]+)"', webpage, 'play info', default=None)
  71. if encrypted_play_info is not None:
  72. # Decode
  73. encrypted_play_info = compat_b64decode(encrypted_play_info)
  74. else:
  75. # New path
  76. full_info_json = self._parse_json(self._html_search_regex(
  77. r'<script id="relay-data" type="text/x-mixcloud">([^<]+)</script>',
  78. webpage, 'play info'), 'play info')
  79. for item in full_info_json:
  80. item_data = try_get(
  81. item, lambda x: x['cloudcast']['data']['cloudcastLookup'],
  82. dict)
  83. if try_get(item_data, lambda x: x['streamInfo']['url']):
  84. info_json = item_data
  85. break
  86. else:
  87. raise ExtractorError('Failed to extract matching stream info')
  88. message = self._html_search_regex(
  89. r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
  90. webpage, 'error message', default=None)
  91. js_url = self._search_regex(
  92. r'<script[^>]+\bsrc=["\"](https://(?:www\.)?mixcloud\.com/media/(?:js2/www_js_4|js/www)\.[^>]+\.js)',
  93. webpage, 'js url')
  94. js = self._download_webpage(js_url, track_id, 'Downloading JS')
  95. # Known plaintext attack
  96. if encrypted_play_info:
  97. kps = ['{"stream_url":']
  98. kpa_target = encrypted_play_info
  99. else:
  100. kps = ['https://', 'http://']
  101. kpa_target = compat_b64decode(info_json['streamInfo']['url'])
  102. for kp in kps:
  103. partial_key = self._decrypt_xor_cipher(kpa_target, kp)
  104. for quote in ["'", '"']:
  105. key = self._search_regex(
  106. r'{0}({1}[^{0}]*){0}'.format(quote, re.escape(partial_key)),
  107. js, 'encryption key', default=None)
  108. if key is not None:
  109. break
  110. else:
  111. continue
  112. break
  113. else:
  114. raise ExtractorError('Failed to extract encryption key')
  115. if encrypted_play_info is not None:
  116. play_info = self._parse_json(self._decrypt_xor_cipher(key, encrypted_play_info), 'play info')
  117. if message and 'stream_url' not in play_info:
  118. raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
  119. song_url = play_info['stream_url']
  120. formats = [{
  121. 'format_id': 'normal',
  122. 'url': song_url
  123. }]
  124. title = self._html_search_regex(r'm-title="([^"]+)"', webpage, 'title')
  125. thumbnail = self._proto_relative_url(self._html_search_regex(
  126. r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail', fatal=False))
  127. uploader = self._html_search_regex(
  128. r'm-owner-name="([^"]+)"', webpage, 'uploader', fatal=False)
  129. uploader_id = self._search_regex(
  130. r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
  131. description = self._og_search_description(webpage)
  132. view_count = str_to_int(self._search_regex(
  133. [r'<meta itemprop="interactionCount" content="UserPlays:([0-9]+)"',
  134. r'/listeners/?">([0-9,.]+)</a>',
  135. r'(?:m|data)-tooltip=["\']([\d,.]+) plays'],
  136. webpage, 'play count', default=None))
  137. else:
  138. title = info_json['name']
  139. thumbnail = urljoin(
  140. 'https://thumbnailer.mixcloud.com/unsafe/600x600/',
  141. try_get(info_json, lambda x: x['picture']['urlRoot'], compat_str))
  142. uploader = try_get(info_json, lambda x: x['owner']['displayName'])
  143. uploader_id = try_get(info_json, lambda x: x['owner']['username'])
  144. description = try_get(info_json, lambda x: x['description'])
  145. view_count = int_or_none(try_get(info_json, lambda x: x['plays']))
  146. stream_info = info_json['streamInfo']
  147. formats = []
  148. for url_key in ('url', 'hlsUrl', 'dashUrl'):
  149. format_url = stream_info.get(url_key)
  150. if not format_url:
  151. continue
  152. decrypted = self._decrypt_xor_cipher(key, compat_b64decode(format_url))
  153. if not decrypted:
  154. continue
  155. if url_key == 'hlsUrl':
  156. formats.extend(self._extract_m3u8_formats(
  157. decrypted, track_id, 'mp4', entry_protocol='m3u8_native',
  158. m3u8_id='hls', fatal=False))
  159. elif url_key == 'dashUrl':
  160. formats.extend(self._extract_mpd_formats(
  161. decrypted, track_id, mpd_id='dash', fatal=False))
  162. else:
  163. formats.append({
  164. 'format_id': 'http',
  165. 'url': decrypted,
  166. })
  167. self._sort_formats(formats)
  168. return {
  169. 'id': track_id,
  170. 'title': title,
  171. 'formats': formats,
  172. 'description': description,
  173. 'thumbnail': thumbnail,
  174. 'uploader': uploader,
  175. 'uploader_id': uploader_id,
  176. 'view_count': view_count,
  177. }
  178. class MixcloudPlaylistBaseIE(InfoExtractor):
  179. _PAGE_SIZE = 24
  180. def _find_urls_in_page(self, page):
  181. for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', page):
  182. yield self.url_result(
  183. compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
  184. MixcloudIE.ie_key())
  185. def _fetch_tracks_page(self, path, video_id, page_name, current_page, real_page_number=None):
  186. real_page_number = real_page_number or current_page + 1
  187. return self._download_webpage(
  188. 'https://www.mixcloud.com/%s/' % path, video_id,
  189. note='Download %s (page %d)' % (page_name, current_page + 1),
  190. errnote='Unable to download %s' % page_name,
  191. query={'page': real_page_number, 'list': 'main', '_ajax': '1'},
  192. headers={'X-Requested-With': 'XMLHttpRequest'})
  193. def _tracks_page_func(self, page, video_id, page_name, current_page):
  194. resp = self._fetch_tracks_page(page, video_id, page_name, current_page)
  195. for item in self._find_urls_in_page(resp):
  196. yield item
  197. def _get_user_description(self, page_content):
  198. return self._html_search_regex(
  199. r'<div[^>]+class="profile-bio"[^>]*>(.+?)</div>',
  200. page_content, 'user description', fatal=False)
  201. class MixcloudUserIE(MixcloudPlaylistBaseIE):
  202. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
  203. IE_NAME = 'mixcloud:user'
  204. _TESTS = [{
  205. 'url': 'http://www.mixcloud.com/dholbach/',
  206. 'info_dict': {
  207. 'id': 'dholbach_uploads',
  208. 'title': 'Daniel Holbach (uploads)',
  209. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  210. },
  211. 'playlist_mincount': 11,
  212. }, {
  213. 'url': 'http://www.mixcloud.com/dholbach/uploads/',
  214. 'info_dict': {
  215. 'id': 'dholbach_uploads',
  216. 'title': 'Daniel Holbach (uploads)',
  217. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  218. },
  219. 'playlist_mincount': 11,
  220. }, {
  221. 'url': 'http://www.mixcloud.com/dholbach/favorites/',
  222. 'info_dict': {
  223. 'id': 'dholbach_favorites',
  224. 'title': 'Daniel Holbach (favorites)',
  225. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  226. },
  227. 'params': {
  228. 'playlist_items': '1-100',
  229. },
  230. 'playlist_mincount': 100,
  231. }, {
  232. 'url': 'http://www.mixcloud.com/dholbach/listens/',
  233. 'info_dict': {
  234. 'id': 'dholbach_listens',
  235. 'title': 'Daniel Holbach (listens)',
  236. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  237. },
  238. 'params': {
  239. 'playlist_items': '1-100',
  240. },
  241. 'playlist_mincount': 100,
  242. }]
  243. def _real_extract(self, url):
  244. mobj = re.match(self._VALID_URL, url)
  245. user_id = mobj.group('user')
  246. list_type = mobj.group('type')
  247. # if only a profile URL was supplied, default to download all uploads
  248. if list_type is None:
  249. list_type = 'uploads'
  250. video_id = '%s_%s' % (user_id, list_type)
  251. profile = self._download_webpage(
  252. 'https://www.mixcloud.com/%s/' % user_id, video_id,
  253. note='Downloading user profile',
  254. errnote='Unable to download user profile')
  255. username = self._og_search_title(profile)
  256. description = self._get_user_description(profile)
  257. entries = OnDemandPagedList(
  258. functools.partial(
  259. self._tracks_page_func,
  260. '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
  261. self._PAGE_SIZE)
  262. return self.playlist_result(
  263. entries, video_id, '%s (%s)' % (username, list_type), description)
  264. class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
  265. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
  266. IE_NAME = 'mixcloud:playlist'
  267. _TESTS = [{
  268. 'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
  269. 'info_dict': {
  270. 'id': 'RedBullThre3style_tokyo-finalists-2015',
  271. 'title': 'National Champions 2015',
  272. 'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
  273. },
  274. 'playlist_mincount': 16,
  275. }, {
  276. 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
  277. 'only_matching': True,
  278. }]
  279. def _real_extract(self, url):
  280. mobj = re.match(self._VALID_URL, url)
  281. user_id = mobj.group('user')
  282. playlist_id = mobj.group('playlist')
  283. video_id = '%s_%s' % (user_id, playlist_id)
  284. webpage = self._download_webpage(
  285. url, user_id,
  286. note='Downloading playlist page',
  287. errnote='Unable to download playlist page')
  288. title = self._html_search_regex(
  289. r'<a[^>]+class="parent active"[^>]*><b>\d+</b><span[^>]*>([^<]+)',
  290. webpage, 'playlist title',
  291. default=None) or self._og_search_title(webpage, fatal=False)
  292. description = self._get_user_description(webpage)
  293. entries = OnDemandPagedList(
  294. functools.partial(
  295. self._tracks_page_func,
  296. '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
  297. self._PAGE_SIZE)
  298. return self.playlist_result(entries, video_id, title, description)
  299. class MixcloudStreamIE(MixcloudPlaylistBaseIE):
  300. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/stream/?$'
  301. IE_NAME = 'mixcloud:stream'
  302. _TEST = {
  303. 'url': 'https://www.mixcloud.com/FirstEar/stream/',
  304. 'info_dict': {
  305. 'id': 'FirstEar',
  306. 'title': 'First Ear',
  307. 'description': 'Curators of good music\nfirstearmusic.com',
  308. },
  309. 'playlist_mincount': 192,
  310. }
  311. def _real_extract(self, url):
  312. user_id = self._match_id(url)
  313. webpage = self._download_webpage(url, user_id)
  314. entries = []
  315. prev_page_url = None
  316. def _handle_page(page):
  317. entries.extend(self._find_urls_in_page(page))
  318. return self._search_regex(
  319. r'm-next-page-url="([^"]+)"', page,
  320. 'next page URL', default=None)
  321. next_page_url = _handle_page(webpage)
  322. for idx in itertools.count(0):
  323. if not next_page_url or prev_page_url == next_page_url:
  324. break
  325. prev_page_url = next_page_url
  326. current_page = int(self._search_regex(
  327. r'\?page=(\d+)', next_page_url, 'next page number'))
  328. next_page_url = _handle_page(self._fetch_tracks_page(
  329. '%s/stream' % user_id, user_id, 'stream', idx,
  330. real_page_number=current_page))
  331. username = self._og_search_title(webpage)
  332. description = self._get_user_description(webpage)
  333. return self.playlist_result(entries, user_id, username, description)