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