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.

191 lines
7.0 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import time
  4. import math
  5. import os.path
  6. import re
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_html_parser,
  10. compat_urllib_parse,
  11. compat_urllib_request,
  12. compat_urlparse,
  13. )
  14. from ..utils import ExtractorError
  15. class GroovesharkHtmlParser(compat_html_parser.HTMLParser):
  16. def __init__(self):
  17. self._current_object = None
  18. self.objects = []
  19. compat_html_parser.HTMLParser.__init__(self)
  20. def handle_starttag(self, tag, attrs):
  21. attrs = dict((k, v) for k, v in attrs)
  22. if tag == 'object':
  23. self._current_object = {'attrs': attrs, 'params': []}
  24. elif tag == 'param':
  25. self._current_object['params'].append(attrs)
  26. def handle_endtag(self, tag):
  27. if tag == 'object':
  28. self.objects.append(self._current_object)
  29. self._current_object = None
  30. @classmethod
  31. def extract_object_tags(cls, html):
  32. p = cls()
  33. p.feed(html)
  34. p.close()
  35. return p.objects
  36. class GroovesharkIE(InfoExtractor):
  37. _VALID_URL = r'https?://(www\.)?grooveshark\.com/#!/s/([^/]+)/([^/]+)'
  38. _TEST = {
  39. 'url': 'http://grooveshark.com/#!/s/Jolene+Tenth+Key+Remix+Ft+Will+Sessions/6SS1DW?src=5',
  40. 'md5': '7ecf8aefa59d6b2098517e1baa530023',
  41. 'info_dict': {
  42. 'id': '6SS1DW',
  43. 'title': 'Jolene (Tenth Key Remix ft. Will Sessions)',
  44. 'ext': 'mp3',
  45. 'duration': 227,
  46. }
  47. }
  48. do_playerpage_request = True
  49. do_bootstrap_request = True
  50. def _parse_target(self, target):
  51. uri = compat_urlparse.urlparse(target)
  52. hash = uri.fragment[1:].split('?')[0]
  53. token = os.path.basename(hash.rstrip('/'))
  54. return (uri, hash, token)
  55. def _build_bootstrap_url(self, target):
  56. (uri, hash, token) = self._parse_target(target)
  57. query = 'getCommunicationToken=1&hash=%s&%d' % (compat_urllib_parse.quote(hash, safe=''), self.ts)
  58. return (compat_urlparse.urlunparse((uri.scheme, uri.netloc, '/preload.php', None, query, None)), token)
  59. def _build_meta_url(self, target):
  60. (uri, hash, token) = self._parse_target(target)
  61. query = 'hash=%s&%d' % (compat_urllib_parse.quote(hash, safe=''), self.ts)
  62. return (compat_urlparse.urlunparse((uri.scheme, uri.netloc, '/preload.php', None, query, None)), token)
  63. def _build_stream_url(self, meta):
  64. return compat_urlparse.urlunparse(('http', meta['streamKey']['ip'], '/stream.php', None, None, None))
  65. def _build_swf_referer(self, target, obj):
  66. (uri, _, _) = self._parse_target(target)
  67. return compat_urlparse.urlunparse((uri.scheme, uri.netloc, obj['attrs']['data'], None, None, None))
  68. def _transform_bootstrap(self, js):
  69. return re.split('(?m)^\s*try\s*\{', js)[0] \
  70. .split(' = ', 1)[1].strip().rstrip(';')
  71. def _transform_meta(self, js):
  72. return js.split('\n')[0].split('=')[1].rstrip(';')
  73. def _get_meta(self, target):
  74. (meta_url, token) = self._build_meta_url(target)
  75. self.to_screen('Metadata URL: %s' % meta_url)
  76. headers = {'Referer': compat_urlparse.urldefrag(target)[0]}
  77. req = compat_urllib_request.Request(meta_url, headers=headers)
  78. res = self._download_json(req, token,
  79. transform_source=self._transform_meta)
  80. if 'getStreamKeyWithSong' not in res:
  81. raise ExtractorError(
  82. 'Metadata not found. URL may be malformed, or Grooveshark API may have changed.')
  83. if res['getStreamKeyWithSong'] is None:
  84. raise ExtractorError(
  85. 'Metadata download failed, probably due to Grooveshark anti-abuse throttling. Wait at least an hour before retrying from this IP.',
  86. expected=True)
  87. return res['getStreamKeyWithSong']
  88. def _get_bootstrap(self, target):
  89. (bootstrap_url, token) = self._build_bootstrap_url(target)
  90. headers = {'Referer': compat_urlparse.urldefrag(target)[0]}
  91. req = compat_urllib_request.Request(bootstrap_url, headers=headers)
  92. res = self._download_json(req, token, fatal=False,
  93. note='Downloading player bootstrap data',
  94. errnote='Unable to download player bootstrap data',
  95. transform_source=self._transform_bootstrap)
  96. return res
  97. def _get_playerpage(self, target):
  98. (_, _, token) = self._parse_target(target)
  99. webpage = self._download_webpage(
  100. target, token,
  101. note='Downloading player page',
  102. errnote='Unable to download player page',
  103. fatal=False)
  104. if webpage is not None:
  105. # Search (for example German) error message
  106. error_msg = self._html_search_regex(
  107. r'<div id="content">\s*<h2>(.*?)</h2>', webpage,
  108. 'error message', default=None)
  109. if error_msg is not None:
  110. error_msg = error_msg.replace('\n', ' ')
  111. raise ExtractorError('Grooveshark said: %s' % error_msg)
  112. if webpage is not None:
  113. o = GroovesharkHtmlParser.extract_object_tags(webpage)
  114. return (webpage, [x for x in o if x['attrs']['id'] == 'jsPlayerEmbed'])
  115. return (webpage, None)
  116. def _real_initialize(self):
  117. self.ts = int(time.time() * 1000) # timestamp in millis
  118. def _real_extract(self, url):
  119. (target_uri, _, token) = self._parse_target(url)
  120. # 1. Fill cookiejar by making a request to the player page
  121. swf_referer = None
  122. if self.do_playerpage_request:
  123. (_, player_objs) = self._get_playerpage(url)
  124. if player_objs is not None:
  125. swf_referer = self._build_swf_referer(url, player_objs[0])
  126. self.to_screen('SWF Referer: %s' % swf_referer)
  127. # 2. Ask preload.php for swf bootstrap data to better mimic webapp
  128. if self.do_bootstrap_request:
  129. bootstrap = self._get_bootstrap(url)
  130. self.to_screen('CommunicationToken: %s' % bootstrap['getCommunicationToken'])
  131. # 3. Ask preload.php for track metadata.
  132. meta = self._get_meta(url)
  133. # 4. Construct stream request for track.
  134. stream_url = self._build_stream_url(meta)
  135. duration = int(math.ceil(float(meta['streamKey']['uSecs']) / 1000000))
  136. post_dict = {'streamKey': meta['streamKey']['streamKey']}
  137. post_data = compat_urllib_parse.urlencode(post_dict).encode('utf-8')
  138. headers = {
  139. 'Content-Length': len(post_data),
  140. 'Content-Type': 'application/x-www-form-urlencoded'
  141. }
  142. if swf_referer is not None:
  143. headers['Referer'] = swf_referer
  144. return {
  145. 'id': token,
  146. 'title': meta['song']['Name'],
  147. 'http_method': 'POST',
  148. 'url': stream_url,
  149. 'ext': 'mp3',
  150. 'format': 'mp3 audio',
  151. 'duration': duration,
  152. 'http_post_data': post_data,
  153. 'http_headers': headers,
  154. }