logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

mixcloud.py (11661B)


  1. from __future__ import unicode_literals
  2. import itertools
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_b64decode,
  7. compat_chr,
  8. compat_ord,
  9. compat_str,
  10. compat_urllib_parse_unquote,
  11. compat_zip
  12. )
  13. from ..utils import (
  14. int_or_none,
  15. parse_iso8601,
  16. strip_or_none,
  17. try_get,
  18. )
  19. class MixcloudBaseIE(InfoExtractor):
  20. def _call_api(self, object_type, object_fields, display_id, username, slug=None):
  21. lookup_key = object_type + 'Lookup'
  22. return self._download_json(
  23. 'https://www.mixcloud.com/graphql', display_id, query={
  24. 'query': '''{
  25. %s(lookup: {username: "%s"%s}) {
  26. %s
  27. }
  28. }''' % (lookup_key, username, ', slug: "%s"' % slug if slug else '', object_fields)
  29. })['data'][lookup_key]
  30. class MixcloudIE(MixcloudBaseIE):
  31. _VALID_URL = r'https?://(?:(?:www|beta|m)\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
  32. IE_NAME = 'mixcloud'
  33. _TESTS = [{
  34. 'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
  35. 'info_dict': {
  36. 'id': 'dholbach_cryptkeeper',
  37. 'ext': 'm4a',
  38. 'title': 'Cryptkeeper',
  39. 'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
  40. 'uploader': 'Daniel Holbach',
  41. 'uploader_id': 'dholbach',
  42. 'thumbnail': r're:https?://.*\.jpg',
  43. 'view_count': int,
  44. 'timestamp': 1321359578,
  45. 'upload_date': '20111115',
  46. },
  47. }, {
  48. 'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
  49. 'info_dict': {
  50. 'id': 'gillespeterson_caribou-7-inch-vinyl-mix-chat',
  51. 'ext': 'mp3',
  52. 'title': 'Caribou 7 inch Vinyl Mix & Chat',
  53. 'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
  54. 'uploader': 'Gilles Peterson Worldwide',
  55. 'uploader_id': 'gillespeterson',
  56. 'thumbnail': 're:https?://.*',
  57. 'view_count': int,
  58. 'timestamp': 1422987057,
  59. 'upload_date': '20150203',
  60. },
  61. }, {
  62. 'url': 'https://beta.mixcloud.com/RedLightRadio/nosedrip-15-red-light-radio-01-18-2016/',
  63. 'only_matching': True,
  64. }]
  65. _DECRYPTION_KEY = 'IFYOUWANTTHEARTISTSTOGETPAIDDONOTDOWNLOADFROMMIXCLOUD'
  66. @staticmethod
  67. def _decrypt_xor_cipher(key, ciphertext):
  68. """Encrypt/Decrypt XOR cipher. Both ways are possible because it's XOR."""
  69. return ''.join([
  70. compat_chr(compat_ord(ch) ^ compat_ord(k))
  71. for ch, k in compat_zip(ciphertext, itertools.cycle(key))])
  72. def _real_extract(self, url):
  73. username, slug = re.match(self._VALID_URL, url).groups()
  74. username, slug = compat_urllib_parse_unquote(username), compat_urllib_parse_unquote(slug)
  75. track_id = '%s_%s' % (username, slug)
  76. cloudcast = self._call_api('cloudcast', '''audioLength
  77. comments(first: 100) {
  78. edges {
  79. node {
  80. comment
  81. created
  82. user {
  83. displayName
  84. username
  85. }
  86. }
  87. }
  88. totalCount
  89. }
  90. description
  91. favorites {
  92. totalCount
  93. }
  94. featuringArtistList
  95. isExclusive
  96. name
  97. owner {
  98. displayName
  99. url
  100. username
  101. }
  102. picture(width: 1024, height: 1024) {
  103. url
  104. }
  105. plays
  106. publishDate
  107. reposts {
  108. totalCount
  109. }
  110. streamInfo {
  111. dashUrl
  112. hlsUrl
  113. url
  114. }
  115. tags {
  116. tag {
  117. name
  118. }
  119. }''', track_id, username, slug)
  120. title = cloudcast['name']
  121. stream_info = cloudcast['streamInfo']
  122. formats = []
  123. for url_key in ('url', 'hlsUrl', 'dashUrl'):
  124. format_url = stream_info.get(url_key)
  125. if not format_url:
  126. continue
  127. decrypted = self._decrypt_xor_cipher(
  128. self._DECRYPTION_KEY, compat_b64decode(format_url))
  129. if url_key == 'hlsUrl':
  130. formats.extend(self._extract_m3u8_formats(
  131. decrypted, track_id, 'mp4', entry_protocol='m3u8_native',
  132. m3u8_id='hls', fatal=False))
  133. elif url_key == 'dashUrl':
  134. formats.extend(self._extract_mpd_formats(
  135. decrypted, track_id, mpd_id='dash', fatal=False))
  136. else:
  137. formats.append({
  138. 'format_id': 'http',
  139. 'url': decrypted,
  140. 'downloader_options': {
  141. # Mixcloud starts throttling at >~5M
  142. 'http_chunk_size': 5242880,
  143. },
  144. })
  145. if not formats and cloudcast.get('isExclusive'):
  146. self.raise_login_required()
  147. self._sort_formats(formats)
  148. comments = []
  149. for edge in (try_get(cloudcast, lambda x: x['comments']['edges']) or []):
  150. node = edge.get('node') or {}
  151. text = strip_or_none(node.get('comment'))
  152. if not text:
  153. continue
  154. user = node.get('user') or {}
  155. comments.append({
  156. 'author': user.get('displayName'),
  157. 'author_id': user.get('username'),
  158. 'text': text,
  159. 'timestamp': parse_iso8601(node.get('created')),
  160. })
  161. tags = []
  162. for t in cloudcast.get('tags'):
  163. tag = try_get(t, lambda x: x['tag']['name'], compat_str)
  164. if not tag:
  165. tags.append(tag)
  166. get_count = lambda x: int_or_none(try_get(cloudcast, lambda y: y[x]['totalCount']))
  167. owner = cloudcast.get('owner') or {}
  168. return {
  169. 'id': track_id,
  170. 'title': title,
  171. 'formats': formats,
  172. 'description': cloudcast.get('description'),
  173. 'thumbnail': try_get(cloudcast, lambda x: x['picture']['url'], compat_str),
  174. 'uploader': owner.get('displayName'),
  175. 'timestamp': parse_iso8601(cloudcast.get('publishDate')),
  176. 'uploader_id': owner.get('username'),
  177. 'uploader_url': owner.get('url'),
  178. 'duration': int_or_none(cloudcast.get('audioLength')),
  179. 'view_count': int_or_none(cloudcast.get('plays')),
  180. 'like_count': get_count('favorites'),
  181. 'repost_count': get_count('reposts'),
  182. 'comment_count': get_count('comments'),
  183. 'comments': comments,
  184. 'tags': tags,
  185. 'artist': ', '.join(cloudcast.get('featuringArtistList') or []) or None,
  186. }
  187. class MixcloudPlaylistBaseIE(MixcloudBaseIE):
  188. def _get_cloudcast(self, node):
  189. return node
  190. def _get_playlist_title(self, title, slug):
  191. return title
  192. def _real_extract(self, url):
  193. username, slug = re.match(self._VALID_URL, url).groups()
  194. username = compat_urllib_parse_unquote(username)
  195. if not slug:
  196. slug = 'uploads'
  197. else:
  198. slug = compat_urllib_parse_unquote(slug)
  199. playlist_id = '%s_%s' % (username, slug)
  200. is_playlist_type = self._ROOT_TYPE == 'playlist'
  201. playlist_type = 'items' if is_playlist_type else slug
  202. list_filter = ''
  203. has_next_page = True
  204. entries = []
  205. while has_next_page:
  206. playlist = self._call_api(
  207. self._ROOT_TYPE, '''%s
  208. %s
  209. %s(first: 100%s) {
  210. edges {
  211. node {
  212. %s
  213. }
  214. }
  215. pageInfo {
  216. endCursor
  217. hasNextPage
  218. }
  219. }''' % (self._TITLE_KEY, self._DESCRIPTION_KEY, playlist_type, list_filter, self._NODE_TEMPLATE),
  220. playlist_id, username, slug if is_playlist_type else None)
  221. items = playlist.get(playlist_type) or {}
  222. for edge in items.get('edges', []):
  223. cloudcast = self._get_cloudcast(edge.get('node') or {})
  224. cloudcast_url = cloudcast.get('url')
  225. if not cloudcast_url:
  226. continue
  227. slug = try_get(cloudcast, lambda x: x['slug'], compat_str)
  228. owner_username = try_get(cloudcast, lambda x: x['owner']['username'], compat_str)
  229. video_id = '%s_%s' % (owner_username, slug) if slug and owner_username else None
  230. entries.append(self.url_result(
  231. cloudcast_url, MixcloudIE.ie_key(), video_id))
  232. page_info = items['pageInfo']
  233. has_next_page = page_info['hasNextPage']
  234. list_filter = ', after: "%s"' % page_info['endCursor']
  235. return self.playlist_result(
  236. entries, playlist_id,
  237. self._get_playlist_title(playlist[self._TITLE_KEY], slug),
  238. playlist.get(self._DESCRIPTION_KEY))
  239. class MixcloudUserIE(MixcloudPlaylistBaseIE):
  240. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/(?P<type>uploads|favorites|listens|stream)?/?$'
  241. IE_NAME = 'mixcloud:user'
  242. _TESTS = [{
  243. 'url': 'http://www.mixcloud.com/dholbach/',
  244. 'info_dict': {
  245. 'id': 'dholbach_uploads',
  246. 'title': 'Daniel Holbach (uploads)',
  247. 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
  248. },
  249. 'playlist_mincount': 36,
  250. }, {
  251. 'url': 'http://www.mixcloud.com/dholbach/uploads/',
  252. 'info_dict': {
  253. 'id': 'dholbach_uploads',
  254. 'title': 'Daniel Holbach (uploads)',
  255. 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
  256. },
  257. 'playlist_mincount': 36,
  258. }, {
  259. 'url': 'http://www.mixcloud.com/dholbach/favorites/',
  260. 'info_dict': {
  261. 'id': 'dholbach_favorites',
  262. 'title': 'Daniel Holbach (favorites)',
  263. 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
  264. },
  265. # 'params': {
  266. # 'playlist_items': '1-100',
  267. # },
  268. 'playlist_mincount': 396,
  269. }, {
  270. 'url': 'http://www.mixcloud.com/dholbach/listens/',
  271. 'info_dict': {
  272. 'id': 'dholbach_listens',
  273. 'title': 'Daniel Holbach (listens)',
  274. 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
  275. },
  276. # 'params': {
  277. # 'playlist_items': '1-100',
  278. # },
  279. 'playlist_mincount': 1623,
  280. 'skip': 'Large list',
  281. }, {
  282. 'url': 'https://www.mixcloud.com/FirstEar/stream/',
  283. 'info_dict': {
  284. 'id': 'FirstEar_stream',
  285. 'title': 'First Ear (stream)',
  286. 'description': 'Curators of good music\r\n\r\nfirstearmusic.com',
  287. },
  288. 'playlist_mincount': 271,
  289. }]
  290. _TITLE_KEY = 'displayName'
  291. _DESCRIPTION_KEY = 'biog'
  292. _ROOT_TYPE = 'user'
  293. _NODE_TEMPLATE = '''slug
  294. url
  295. owner { username }'''
  296. def _get_playlist_title(self, title, slug):
  297. return '%s (%s)' % (title, slug)
  298. class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
  299. _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
  300. IE_NAME = 'mixcloud:playlist'
  301. _TESTS = [{
  302. 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
  303. 'info_dict': {
  304. 'id': 'maxvibes_jazzcat-on-ness-radio',
  305. 'title': 'Ness Radio sessions',
  306. },
  307. 'playlist_mincount': 59,
  308. }]
  309. _TITLE_KEY = 'name'
  310. _DESCRIPTION_KEY = 'description'
  311. _ROOT_TYPE = 'playlist'
  312. _NODE_TEMPLATE = '''cloudcast {
  313. slug
  314. url
  315. owner { username }
  316. }'''
  317. def _get_cloudcast(self, node):
  318. return node.get('cloudcast') or {}