Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 101 lines (84 sloc) 3.656 kb
cc9af55 Kevin Ngo renamed to soundcloud-dl, fixed shebang
authored
1 #!/usr/bin/python
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
2
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
3 from optparse import OptionParser
89f85a0 Kevin Ngo finish. now successfully downloads .mp3 files and saves it to file. need...
authored
4 import cookielib
5 import urllib2
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
6 import sys
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
7 import re
c325916 Jacques Uber Changes:
uberj authored
8 import time
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
9 import random
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
10
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
11 # Maximum number of download attempts
c325916 Jacques Uber Changes:
uberj authored
12 MAX_NUMBER_OF_TRIES = 3
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
13 # Alphabet for random file names.
14 alpha = "abcdefghijklmnopqrstuvwxyz"
15 R_LEN = 5 # Length of random name
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
16 # set up header values and openers
17 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'}
18 cj = cookielib.MozillaCookieJar()
19 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPHandler())
20 urllib2.install_opener(opener)
21
22 def open_url(url):
23 retry = 0;
24 while retry < 3:
25 request = urllib2.Request(options.url, headers=header_values)
c325916 Jacques Uber Changes:
uberj authored
26 try:
27 response = opener.open(request)
28 except urllib2.HTTPError, e:
29 print "Failed to fetch url. "+str(e)
30 return None
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
31 html = response.read()
32 if not html:
33 retry += 1
34 continue
35 break
36 return html
37
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
38 def get_stream_token_uid(page):
39 """ returns stream token and uid as tuple """
40 match = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', page)
c325916 Jacques Uber Changes:
uberj authored
41 if match:
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
42 uid = match.group(1)
43 stream_token = match.group(2)
44 return (uid, stream_token)
45
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
46 def get_song_title(page, sain_name=False, random_name=False):
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
47 match = re.search('(?<=\"title\":\").*?(?=\")', page)
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
48 if match and not random_name:
c325916 Jacques Uber Changes:
uberj authored
49 if sain_name:
50 return match.group(0).replace(' ','_')
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
51 return match.group(0)
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
52 else:
53 return ''.join(random.choice(alpha) for i in xrange(R_LEN))
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
54
55 def download(uid, token, song_title='soundcloud_dl.mp3'):
89f85a0 Kevin Ngo finish. now successfully downloads .mp3 files and saves it to file. need...
authored
56 """ given url with token and uid, download file to mp3 """
57
c325916 Jacques Uber Changes:
uberj authored
58 # compose a url with uid and token and request the mpeg
89f85a0 Kevin Ngo finish. now successfully downloads .mp3 files and saves it to file. need...
authored
59 url = "http://media.soundcloud.com/stream/%s?stream_token=%s" % (uid, token)
60 request = urllib2.Request(url, headers=header_values)
61 response = opener.open(request)
62
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
63 f = open(song_title, 'w')
89f85a0 Kevin Ngo finish. now successfully downloads .mp3 files and saves it to file. need...
authored
64 f.write(response.read())
65
66
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
67 if __name__ == '__main__':
68
69 parser = OptionParser()
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
70 parser.add_option("-u", "--url", help="soundcloud url to download", dest="url")
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
71 parser.add_option("-n", "--sain-name", action="store_true", help="change all spaces to underscores", dest="sain_name", default=False)
72 parser.add_option("-r", "--random-name", action="store_true", help="use a random file name when writing file", dest="random_name", default=False)
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
73 (options, args) = parser.parse_args()
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
74 if not options.url:
75 parser.error("--url option requires an argument")
c325916 Jacques Uber Changes:
uberj authored
76
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
77 # open up initial page to get stream token, uid, song title
78 html = open_url(options.url)
79 if not html:
80 sys.exit()
c325916 Jacques Uber Changes:
uberj authored
81 tries = 0
82 while True:
83 info = get_stream_token_uid(html)
84 tries += 1
85 if info:
86 break
87 elif tries > MAX_NUMBER_OF_TRIES:
88 print "Failed after %s attemps to fetch token and uid." % (tries)
89 sys.exit(1) # We need to do this loop in a function.
90 else:
91 time.sleep(tries)
92
93 uid, token = info
aae03b4 Jacques Uber Added random name generator. This will be usefull if you want random nam...
uberj authored
94 song_title = get_song_title(html, options.sain_name, options.random_name) + '.mp3'
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
95
89f85a0 Kevin Ngo finish. now successfully downloads .mp3 files and saves it to file. need...
authored
96 # the browser does this...so we will too
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
97 open_url('http://media.soundcloud.com/crossdomain.xml')
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
98
48dbfb3 Kevin Ngo encapsulated soundcloud for usability. added some exception handling
authored
99 download(uid, token, song_title)
4a4b13d Kevin Ngo initial commit, can't get cookies out
authored
100
Something went wrong with that request. Please try again.