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.

398 lines
15 KiB

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