#!/usr/bin/env python

"""
Dubstream Downloader
(c) Copyright 2008, Braydon Fuller
http://braydon.com

This is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

import urllib2
import optparse
import sys

class URLHasNoAudio(Exception):
    pass

def extract_mp3_url_from(url):
    page = urllib2.urlopen(url).read()
    start = page.find('soundFile=')
    if start <= 0:
        raise URLHasNoAudio()
    else:
        start = start + 10
    end = start + int(page[start:-1].find('" />'))
    return page[start:end].replace('%2F','/').replace('%3A',':')

def extract_filename_from(url):
    is_dir = True
    while is_dir:
        start = url.find('/')+1
        end = len(url)
        if start:
            url = url[start:end]
        else:
            is_dir = False
    return url

cmdl_usage = 'usage: %prog [options] dubstream_url download_to_dir'
cmdl_version = '2008.04.12'
cmdl_parser = optparse.OptionParser(usage=cmdl_usage, version=cmdl_version, conflict_handler='resolve')
(cmdl_opts, cmdl_args) = cmdl_parser.parse_args()

if len(cmdl_args) != 2:
	cmdl_parser.print_help()
	sys.exit('\n')
dubstream_url = cmdl_args[0]
file_dir = cmdl_args[1]
url = extract_mp3_url_from(dubstream_url)
print  "downloading: %s" % url

filename = extract_filename_from(url)
file = open(file_dir+filename,'w')
file.write(urllib2.urlopen(url).read())
file.close()





