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.

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