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.

392 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. for url_key in ('url', 'hlsUrl', 'dashUrl'):
  148. format_url = stream_info.get(url_key)
  149. if not format_url:
  150. continue
  151. decrypted = self._decrypt_xor_cipher(key, compat_b64decode(format_url))
  152. if not decrypted:
  153. continue
  154. if url_key == 'hlsUrl':
  155. formats.extend(self._extract_m3u8_formats(
  156. decrypted, track_id, 'mp4', entry_protocol='m3u8_native',
  157. m3u8_id='hls', fatal=False))
  158. elif url_key == 'dashUrl':
  159. formats.extend(self._extract_mpd_formats(
  160. decrypted, track_id, mpd_id='dash', fatal=False))
  161. else:
  162. formats.append({
  163. 'format_id': 'http',
  164. 'url': decrypted,
  165. 'downloader_options': {
  166. # Mixcloud starts throttling at >~5M
  167. 'http_chunk_size': 5242880,
  168. },
  169. })
  170. self._sort_formats(formats)
  171. return {
  172. 'id': track_id,
  173. 'title': title,
  174. 'formats': formats,
  175. 'description': description,
  176. 'thumbnail': thumbnail,
  177. 'uploader': uploader,
  178. 'uploader_id': uploader_id,
  179. 'view_count': view_count,
  180. }
  181. class MixcloudPlaylistBaseIE(InfoExtractor):
  182. _PAGE_SIZE = 24
  183. def _find_urls_in_page(self, page):
  184. for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', page):
  185. yield self.url_result(
  186. compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
  187. MixcloudIE.ie_key())
  188. def _fetch_tracks_page(self, path, video_id, page_name, current_page, real_page_number=None):
  189. real_page_number = real_page_number or current_page + 1
  190. return self._download_webpage(
  191. 'https://www.mixcloud.com/%s/' % path, video_id,
  192. note='Download %s (page %d)' % (page_name, current_page + 1),
  193. errnote='Unable to download %s' % page_name,
  194. query={'page': real_page_number, 'list': 'main', '_ajax': '1'},
  195. headers={'X-Requested-With': 'XMLHttpRequest'})
  196. def _tracks_page_func(self, page, video_id, page_name, current_page):
  197. resp = self._fetch_tracks_page(page, video_id, page_name, current_page)
  198. for item in self._find_urls_in_page(resp):
  199. yield item
  200. def _get_user_description(self, page_content):
  201. return self._html_search_regex(
  202. r'<div[^>]+class="profile-bio"[^>]*>(.+?)</div>',
  203. page_content, 'user description', fatal=False)
  204. class MixcloudUserIE(MixcloudPlaylistBaseIE):
  205. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
  206. IE_NAME = 'mixcloud:user'
  207. _TESTS = [{
  208. 'url': 'http://www.mixcloud.com/dholbach/',
  209. 'info_dict': {
  210. 'id': 'dholbach_uploads',
  211. 'title': 'Daniel Holbach (uploads)',
  212. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  213. },
  214. 'playlist_mincount': 11,
  215. }, {
  216. 'url': 'http://www.mixcloud.com/dholbach/uploads/',
  217. 'info_dict': {
  218. 'id': 'dholbach_uploads',
  219. 'title': 'Daniel Holbach (uploads)',
  220. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  221. },
  222. 'playlist_mincount': 11,
  223. }, {
  224. 'url': 'http://www.mixcloud.com/dholbach/favorites/',
  225. 'info_dict': {
  226. 'id': 'dholbach_favorites',
  227. 'title': 'Daniel Holbach (favorites)',
  228. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  229. },
  230. 'params': {
  231. 'playlist_items': '1-100',
  232. },
  233. 'playlist_mincount': 100,
  234. }, {
  235. 'url': 'http://www.mixcloud.com/dholbach/listens/',
  236. 'info_dict': {
  237. 'id': 'dholbach_listens',
  238. 'title': 'Daniel Holbach (listens)',
  239. 'description': 'md5:def36060ac8747b3aabca54924897e47',
  240. },
  241. 'params': {
  242. 'playlist_items': '1-100',
  243. },
  244. 'playlist_mincount': 100,
  245. }]
  246. def _real_extract(self, url):
  247. mobj = re.match(self._VALID_URL, url)
  248. user_id = mobj.group('user')
  249. list_type = mobj.group('type')
  250. # if only a profile URL was supplied, default to download all uploads
  251. if list_type is None:
  252. list_type = 'uploads'
  253. video_id = '%s_%s' % (user_id, list_type)
  254. profile = self._download_webpage(
  255. 'https://www.mixcloud.com/%s/' % user_id, video_id,
  256. note='Downloading user profile',
  257. errnote='Unable to download user profile')
  258. username = self._og_search_title(profile)
  259. description = self._get_user_description(profile)
  260. entries = OnDemandPagedList(
  261. functools.partial(
  262. self._tracks_page_func,
  263. '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
  264. self._PAGE_SIZE)
  265. return self.playlist_result(
  266. entries, video_id, '%s (%s)' % (username, list_type), description)
  267. class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
  268. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
  269. IE_NAME = 'mixcloud:playlist'
  270. _TESTS = [{
  271. 'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
  272. 'info_dict': {
  273. 'id': 'RedBullThre3style_tokyo-finalists-2015',
  274. 'title': 'National Champions 2015',
  275. 'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
  276. },
  277. 'playlist_mincount': 16,
  278. }, {
  279. 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
  280. 'only_matching': True,
  281. }]
  282. def _real_extract(self, url):
  283. mobj = re.match(self._VALID_URL, url)
  284. user_id = mobj.group('user')
  285. playlist_id = mobj.group('playlist')
  286. video_id = '%s_%s' % (user_id, playlist_id)
  287. webpage = self._download_webpage(
  288. url, user_id,
  289. note='Downloading playlist page',
  290. errnote='Unable to download playlist page')
  291. title = self._html_search_regex(
  292. r'<a[^>]+class="parent active"[^>]*><b>\d+</b><span[^>]*>([^<]+)',
  293. webpage, 'playlist title',
  294. default=None) or self._og_search_title(webpage, fatal=False)
  295. description = self._get_user_description(webpage)
  296. entries = OnDemandPagedList(
  297. functools.partial(
  298. self._tracks_page_func,
  299. '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
  300. self._PAGE_SIZE)
  301. return self.playlist_result(entries, video_id, title, description)
  302. class MixcloudStreamIE(MixcloudPlaylistBaseIE):
  303. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/stream/?$'
  304. IE_NAME = 'mixcloud:stream'
  305. _TEST = {
  306. 'url': 'https://www.mixcloud.com/FirstEar/stream/',
  307. 'info_dict': {
  308. 'id': 'FirstEar',
  309. 'title': 'First Ear',
  310. 'description': 'Curators of good music\nfirstearmusic.com',
  311. },
  312. 'playlist_mincount': 192,
  313. }
  314. def _real_extract(self, url):
  315. user_id = self._match_id(url)
  316. webpage = self._download_webpage(url, user_id)
  317. entries = []
  318. prev_page_url = None
  319. def _handle_page(page):
  320. entries.extend(self._find_urls_in_page(page))
  321. return self._search_regex(
  322. r'm-next-page-url="([^"]+)"', page,
  323. 'next page URL', default=None)
  324. next_page_url = _handle_page(webpage)
  325. for idx in itertools.count(0):
  326. if not next_page_url or prev_page_url == next_page_url:
  327. break
  328. prev_page_url = next_page_url
  329. current_page = int(self._search_regex(
  330. r'\?page=(\d+)', next_page_url, 'next page number'))
  331. next_page_url = _handle_page(self._fetch_tracks_page(
  332. '%s/stream' % user_id, user_id, 'stream', idx,
  333. real_page_number=current_page))
  334. username = self._og_search_title(webpage)
  335. description = self._get_user_description(webpage)
  336. return self.playlist_result(entries, user_id, username, description)