# coding: utf-8 from __future__ import unicode_literals import time import math import re from urllib import quote, urlencode from os.path import basename from .common import InfoExtractor from ..utils import ExtractorError, compat_urllib_request, compat_html_parser from ..utils import compat_urlparse urlunparse = compat_urlparse.urlunparse urldefrag = compat_urlparse.urldefrag class GroovesharkHtmlParser(compat_html_parser.HTMLParser): def __init__(self): self._current_object = None self.objects = [] compat_html_parser.HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): attrs = dict((k, v) for k, v in attrs) if tag == 'object': self._current_object = {'attrs': attrs, 'params': []} elif tag == 'param': self._current_object['params'].append(attrs) def handle_endtag(self, tag): if tag == 'object': self.objects.append(self._current_object) self._current_object = None @classmethod def extract_object_tags(cls, html): p = cls() p.feed(html) p.close() return p.objects class GroovesharkIE(InfoExtractor): _VALID_URL = r'https?://(www\.)?grooveshark\.com/#!/s/([^/]+)/([^/]+)' _TEST = { 'url': 'http://grooveshark.com/#!/s/Jolene+Tenth+Key+Remix+Ft+Will+Sessions/6SS1DW?src=5', 'md5': 'bbccc50b19daca23b8f961152c1dc95b', 'info_dict': { 'id': '6SS1DW', 'title': 'Jolene (Tenth Key Remix ft. Will Sessions)', 'ext': 'mp3', 'duration': 227, } } do_playerpage_request = True do_bootstrap_request = True def _parse_target(self, target): uri = compat_urlparse.urlparse(target) hash = uri.fragment[1:].split('?')[0] token = basename(hash.rstrip('/')) return (uri, hash, token) def _build_bootstrap_url(self, target): (uri, hash, token) = self._parse_target(target) query = 'getCommunicationToken=1&hash=%s&%d' % (quote(hash, safe=''), self.ts) return (urlunparse((uri.scheme, uri.netloc, '/preload.php', None, query, None)), token) def _build_meta_url(self, target): (uri, hash, token) = self._parse_target(target) query = 'hash=%s&%d' % (quote(hash, safe=''), self.ts) return (urlunparse((uri.scheme, uri.netloc, '/preload.php', None, query, None)), token) def _build_stream_url(self, meta): return urlunparse(('http', meta['streamKey']['ip'], '/stream.php', None, None, None)) def _build_swf_referer(self, target, obj): (uri, _, _) = self._parse_target(target) return urlunparse((uri.scheme, uri.netloc, obj['attrs']['data'], None, None, None)) def _transform_bootstrap(self, js): return re.split('(?m)^\s*try\s*{', js)[0] \ .split(' = ', 1)[1].strip().rstrip(';') def _transform_meta(self, js): return js.split('\n')[0].split('=')[1].rstrip(';') def _get_meta(self, target): (meta_url, token) = self._build_meta_url(target) self.to_screen('Metadata URL: %s' % meta_url) headers = {'Referer': urldefrag(target)[0]} req = compat_urllib_request.Request(meta_url, headers=headers) res = self._download_json(req, token, transform_source=self._transform_meta) if 'getStreamKeyWithSong' not in res: raise ExtractorError( 'Metadata not found. URL may be malformed, or Grooveshark API may have changed.') if res['getStreamKeyWithSong'] is None: raise ExtractorError( 'Metadata download failed, probably due to Grooveshark anti-abuse throttling. Wait at least an hour before retrying from this IP.', expected=True) return res['getStreamKeyWithSong'] def _get_bootstrap(self, target): (bootstrap_url, token) = self._build_bootstrap_url(target) headers = {'Referer': urldefrag(target)[0]} req = compat_urllib_request.Request(bootstrap_url, headers=headers) res = self._download_json(req, token, fatal=False, note='Downloading player bootstrap data', errnote='Unable to download player bootstrap data', transform_source=self._transform_bootstrap) return res def _get_playerpage(self, target): (_, _, token) = self._parse_target(target) webpage = self._download_webpage( target, token, note='Downloading player page', errnote='Unable to download player page', fatal=False) if webpage is not None: # Search (for example German) error message error_msg = self._html_search_regex( r'