Permalink
Browse files

finish. now successfully downloads .mp3 files and saves it to file. n…

…eed to regex out title of song. (with much help from thedjpetersen and uberj
  • Loading branch information...
1 parent 4a4b13d commit 89f85a0af43f3b1f7aa0300b5e0efe4ec04e58ed Kevin Ngo committed Nov 5, 2011
Showing with 27 additions and 15 deletions.
  1. +27 −15 soundcloud.py
View
42 soundcloud.py
@@ -1,10 +1,8 @@
from optparse import OptionParser
-import mechanize
+import cookielib
+import urllib2
import re
-def open_page(url):
- return mechanize.urlopen(url)
-
def get_stream_token_uid(page):
""" returns stream token and uid as tuple """
match = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', page)
@@ -13,26 +11,40 @@ def get_stream_token_uid(page):
stream_token = match.group(2)
return (uid, stream_token)
+def download(uid, token)
+ """ given url with token and uid, download file to mp3 """
+
+ url = "http://media.soundcloud.com/stream/%s?stream_token=%s" % (uid, token)
+ request = urllib2.Request(url, headers=header_values)
+ response = opener.open(request)
+
+ f = open('test.mp3', 'w')
+ f.write(response.read())
+
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-u", "--url")
(options, args) = parser.parse_args()
- cj = mechanize.LWPCookieJar()
- opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
- mechanize.install_opener(opener)
-
- browser = mechanize.Browser(factory=mechanize.RobustFactory())
- browser.open(options.url)
- html = browser.response().get_data()
+ # set up header values and openers
+ header_values = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16', 'Accept' : 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding' : 'gzip,deflate,sdch', 'Accept-Language' : 'en-US,en;q=0.8', 'Cache-Control' : 'max-age=0', 'Connection' : 'keep-alive'}
+ cj = cookielib.MozillaCookieJar()
+ opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPHandler())
+ urllib2.install_opener(opener)
- # HOW GET COOKIE?
+ # open up initial page (argument) to get stream token and uid
+ request = urllib2.Request(options.url, headers=header_values)
+ response = opener.open(request)
+ html = response.read()
+ (uid, token) = get_stream_token_uid(html)
- #page = open_page(options.url).read()
- #(uid, stream_token) = get_stream_token_uid(page)
+ # the browser does this...so we will too
+ request = urllib2.Request('http://media.soundcloud.com/crossdomain.xml', headers=header_values)
+ response = opener.open(request)
- #url = "http://media.soundcloud.com/stream/%s?stream_token=%s" % (uid, stream_token)
+ # compose a url with uid and token and request the mpeg
+ download(uid, token)

0 comments on commit 89f85a0

Please sign in to comment.