Download a song respecting Grooveshark's API.

        :return: The raw song data.
344474
def safe_download(self):
        
        def _markStreamKeyOver30Seconds(stream):
            self._connection.request(
                'markStreamKeyOver30Seconds',
                {'streamServerID': stream.ip,
                 'artistID': self.artist.id,
                 'songQueueID': self._connection.session.queue,
                 'songID': self.id,
                 'songQueueSongID': 1,
                 'streamKey': stream.key},
                self._connection.header('markStreamKeyOver30Seconds', 'jsqueue'))

        stream = self.stream
        timer = threading.Timer(30, _markStreamKeyOver30Seconds, [stream])
        timer.start()
        raw = stream.data.read()
        if len(raw) == stream.size:
            timer.cancel()
            self._connection.request(
                'markSongDownloadedEx',
                {'streamServerID': stream.ip,
                 'songID': self.id,
                 'streamKey': stream.key},
                self._connection.header('markSongDownloadedEx', 'jsqueue'))
            self._connection.request(
                'removeSongsFromQueue',
                {'userRemoved': True,
                 'songQueueID': self._connection.session.queue,
                 'songQueueSongIDs': [1]},
                self._connection.header('removeSongsFromQueue', 'jsqueue'))
            return raw
        else:
            raise ValueError("Content-Length {}, but read {}"
                             .format(stream.size, len(raw)))
334163
def download_data
      scraper_data = {}

      @data_to_get.each do |data_category|
        if /liked_(.*)/ =~ data_category
          argument = $1.to_sym  # :tracks, :artists, :stations or :albums
          scraper_data[data_category] = @scraper.public_send(:likes, argument)
        else
          scraper_data[data_category] = @scraper.public_send(data_category)
        end
      end

      scraper_data
    end
1132705
def download_playlist_by_search(self, playlist_name):
        

        try:
            playlist = self.crawler.search_playlist(
                playlist_name, self.quiet)
        except RequestException as exception:
            click.echo(exception)
        else:
            self.download_playlist_by_id(
                playlist.playlist_id, playlist.playlist_name)
1224988
def _get_data_raw(self):
        
        # Import need to be here so we can monkeypatch urlopen for testing and avoid
        # downloading live data for testing
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        with closing(urlopen(self.ftpsite + self.site_id + self.suffix + '.zip')) as url:
            f = ZipFile(BytesIO(url.read()), 'r').open(self.site_id + self.suffix)

        lines = [line.decode('utf-8') for line in f.readlines()]

        body, header, dates_long, dates = self._select_date_range(lines)

        return body, header, dates_long, dates
45737
def download(self):
        
        self.housekeeping()
        self.rippled_history()
        if self.resampling_frequencies is not None:
            self.find_markets()
            self.resample_time_series()
966556
def download_file(self, url):
        
        response = requests.get(url, stream=True)
        response.raise_for_status()
        return (int(response.headers.get('content-length', 0)), response)
1325899
def download(self, uuid, url, forced_file_name=None,
                 progress_bar=True, chunk_size=256,
                 directory=None, overwrite=False):
        
        self.last_req_time = None
        url = self.get_full_url(url)
        self.log.debug("download url : " + url)
        # Building request
        request = urllib2.Request(url)
        # request.add_header('Content-Type', 'application/json; charset=UTF-8')
        request.add_header('Accept', 'application/json,*/*;charset=UTF-8')
        # request start
        starttime = datetime.datetime.now()
        # doRequest
        resultq = urllib2.urlopen(request)
        code = resultq.getcode()
        file_name = uuid
        self.log.debug("ret code : '" + str(code) + "'")
        if code == 200:
            content_lenth = resultq.info().getheader('Content-Length')
            if not content_lenth:
                msg = "No content lengh header found !"
                self.log.debug(msg)
                progress_bar = False
            else:
                file_size = int(content_lenth.strip())
            if forced_file_name:
                file_name = forced_file_name
            else:
                content_dispo = resultq.info().getheader('Content-disposition')
                if content_dispo:
                    content_dispo = content_dispo.strip()
                    file_name = extract_file_name(content_dispo)
            if directory:
                if os.path.isdir(directory):
                    file_name = directory + "/" + file_name
            if os.path.isfile(file_name):
                if not overwrite:
                    cpt = 1
                    while 1:
                        if not os.path.isfile(file_name + "." + str(cpt)):
                            file_name += "." + str(cpt)
                            break
                        cpt += 1
                else:
                    self.log.warn("'%s' already exists. It was overwriten.",
                                  file_name)
            stream = None
            pbar = None
            if progress_bar:
                widgets = [FileTransferSpeed(), ' <<<', Bar(), '>>> ',
                           Percentage(), ' ', ETA()]
                pbar = ProgressBar(widgets=widgets, maxval=file_size)
                stream = FileWithCallback(file_name, 'w', pbar.update,
                                          file_size, file_name)
                pbar.start()
            else:
                stream = file(file_name, 'w')
            while 1:
                chunk = resultq.read(chunk_size)
                if not chunk:
                    break
                stream.write(chunk)
            stream.flush()
            stream.close()
            if pbar:
                pbar.finish()
        # request end
        endtime = datetime.datetime.now()
        self.last_req_time = str(endtime - starttime)
        self.log.debug("download url : %(url)s : request time : %(time)s",
                       {"url": url,
                        "time": self.last_req_time})
        return (file_name, self.last_req_time)
595599
def get_soundcloud_data(url):
    

    data = {}

    request = requests.get(url)

    title_tag = request.text.split('<title>')[1].split('</title')[0]
    data['title'] = title_tag.split(' by ')[0].strip()
    data['artist'] = title_tag.split(' by ')[1].split('|')[0].strip()
    # XXX Do more..

    return data
452222
def requests_url(self, ptype, **data):
        
        options = {
            'type': ptype,
            'pt': '3.1',
            'channel': self._channel_id,
            'pb': '320',
            'from': 'mainsite',
            'r': '',
            'kbps': '320',
            'app_name': 'radio_website',
            'client': 's:mainsite|y:3.0',
            'version': '100'
        }
        if 'sid' in data:
            options['sid'] = data['sid']
        url = 'https://douban.fm/j/v2/playlist'
        while True:
            try:
                s = requests.get(url, params=options,
                                 cookies=self._cookies, headers=HEADERS)
                req_json = s.json()
                if req_json['r'] == 0:
                    if 'song' not in req_json or not req_json['song']:
                        break
                    return req_json['song'][0]
            except Exception as err:
                raise APIError(err)
                break
        return None
428354
def get_audiomack_data(url):
    

    data = {}
    request = requests.get(url)

    mp3_url = request.text.split('class="player-icon download-song" title="Download" href="')[1].split('"')[0]
    artist = request.text.split('<span class="artist">')[1].split('</span>')[0].strip()
    title = request.text.split('<span class="artist">')[1].split('</span>')[1].split('</h1>')[0].strip()
    artwork_url = request.text.split('<a class="lightbox-trigger" href="')[1].split('" data')[0].strip()

    data['mp3_url'] = mp3_url
    data['title'] = title
    data['artist'] = artist
    data['artwork_url'] = artwork_url
    data['year'] = None

    return data
30015
def download(url, filename, redownload):
    
    data_folder, filename = filename.rsplit('/', 1)
    download_list = [DownloadRequest(url=url, data_folder=data_folder, filename=filename, save_response=True,
                                     return_data=False)]
    download_data(download_list, redownload=redownload)
241495
def _download_raw(self, url=None):
        """"""
        if url is None:
            url = self.url
        req = request.Request(url, headers=self.HEADERS_PLAIN)
        return request.urlopen(req).read().decode("utf8")
329823
def download(self):
        
        _, ext = os.path.splitext(self.url)
        if ext == ".mp3":
            self.output_extention = "mp3"
        else:
            self.output_extention = "mp4"  # this might be wrong..
        data = self.http.request("get", self.url, stream=True)
        try:
            total_size = data.headers['content-length']
        except KeyError:
            total_size = 0
        total_size = int(total_size)
        bytes_so_far = 0

        file_d = output(self.output, self.config, self.output_extention)
        if file_d is None:
            return

        eta = ETA(total_size)
        for i in data.iter_content(8192):
            bytes_so_far += len(i)
            file_d.write(i)
            if not self.config.get("silent"):
                eta.update(bytes_so_far)
                progressbar(total_size, bytes_so_far, ''.join(["ETA: ", str(eta)]))

        file_d.close()
        self.finished = True
82948
def main():
    '''
    
    '''

    system('clear') # Must be system('cls') for windows

    setup()

    parser = argparse.ArgumentParser(
        description='Download songs with album art and metadata!')
    parser.add_argument('-c', '--config', action='store_true',
                        help='Set your API keys')
    parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
                        help='Download multiple songs from a text file list')
    parser.add_argument('-a', '--auto', action='store_true',
                        help='Automatically chooses top result')
    parser.add_argument('--album', action='store_true',
                        help='Downloads all songs from an album')
    args = parser.parse_args()
    arg_multiple = args.multiple_file or None
    arg_auto = args.auto or None
    arg_album = args.album or None
    arg_config = args.config


    if arg_config:
        add_config()

    elif arg_multiple and arg_album:
        log.log_error("Can't do both!")

    elif arg_album:
        album_name = input('Enter album name : ')
        try:
            tracks = get_tracks_from_album(album_name)
            for songs in tracks:
                print(songs)
            confirm = input(
                '\nAre these the songs you want to download? (Y/n)\n> ')

        except IndexError:
            log.log_error("Couldn't find album")
            exit()

        if confirm == '' or confirm.lower() == ('y'):
            for track_name in tracks:
                track_name = track_name + ' song'
                song_url, file_name = get_url(track_name, arg_auto)
                download_song(song_url, file_name)
                system('clear')
                repair.fix_music(file_name + '.mp3')

        elif confirm.lower() == 'n':
            log.log_error("Sorry, if appropriate results weren't found")
            exit()
        else:
            log.log_error('Invalid Input')
            exit()

    elif arg_multiple:
        with open(arg_multiple, "r") as f:
            file_names = []
            for line in f:
                file_names.append(line.rstrip('\n'))

        for files in file_names:
            files = files + ' song'
            song_url, file_name = get_url(files, arg_auto)
            download_song(song_url, file_name)
            system('clear')
            repair.fix_music(file_name + '.mp3')

    else:
        query = input('Enter Song Name : ')
        song_url, file_name = get_url(query, arg_auto)  # Gets YT url
        download_song(song_url, file_name)  # Saves as .mp3 file
        system('clear')
        repair.fix_music(file_name + '.mp3')
35054
def download_playlist(playlist):
    
    global arguments
    invalid_chars = '\/:*?|<>"'
    playlist_name = playlist['title'].encode('utf-8', 'ignore')
    playlist_name = playlist_name.decode('utf8')
    playlist_name = ''.join(c for c in playlist_name if c not in invalid_chars)

    if not arguments['--no-playlist-folder']:
        if not os.path.exists(playlist_name):
            os.makedirs(playlist_name)
        os.chdir(playlist_name)

    try:
        with codecs.open(playlist_name + '.m3u', 'w+', 'utf8') as playlist_file:
            playlist_file.write('#EXTM3U' + os.linesep)
            del playlist['tracks'][:offset - 1]
            for counter, track_raw in enumerate(playlist['tracks'], offset):
                logger.debug(track_raw)
                logger.info('Track n°{0}'.format(counter))
                download_track(track_raw, playlist['title'], playlist_file)
    finally:
        os.chdir('..')
18631
def _download(url):
    
    fh = StringIO()

    for line in get(url):
        fh.write(line)

    fh.seek(0)
    return fh
944957
def download(self, media_id, as_stream=False):
        
        response = self.__app.native_api_call('media', 'd/' + media_id, {}, self.__options, False, None, as_stream, http_path="/api/meta/v1/", http_method='GET')
        return response