Download user items of dl_type (ie. all, playlists, liked, commented, etc.)
775311
def download(user, dl_type, name):
    
    username = user['username']
    user_id = user['id']
    logger.info(
        'Retrieving all {0} of user {1}...'.format(name, username)
    )
    dl_url = url[dl_type].format(user_id)
    logger.debug(dl_url)
    resources = client.get_collection(dl_url, token)
    del resources[:offset - 1]
    logger.debug(resources)
    total = len(resources)
    logger.info('Retrieved {0} {1}'.format(total, name))
    for counter, item in enumerate(resources, offset):
        try:
            logger.debug(item)
            logger.info('{0} n°{1} of {2}'.format(
                name.capitalize(), counter, total)
            )
            if dl_type == 'all':
                item_name = item['type'].split('-')[0]  # remove the '-repost'
                uri = item[item_name]['uri']
                parse_url(uri)
            elif dl_type == 'playlists':
                download_playlist(item)
            elif dl_type == 'playlists-liked':
                parse_url(item['playlist']['uri'])
            elif dl_type == 'commented':
                item = get_track_info(item['track_id'])
                download_track(item)
            else:
                download_track(item)
        except Exception as e:
            logger.exception(e)
    logger.info('Downloaded all {0} {1} of user {2}!'.format(
        total, name, username)
    )
681808
def getent(refresh=False):
    '''
    
    '''
    if 'user.getent' in __context__ and not refresh:
        return __context__['user.getent']

    ret = []
    for data in pwd.getpwall():
        ret.append(_format_info(data))
    __context__['user.getent'] = ret
    return ret
1304887
function downloadNames(src, name, callback) {
    async.waterfall([
        function (callback) {
            request.get({
                url: src
            }, callback);
        },
        function (res, html, callback) {
            var $ = cheerio.load(html);
            callback(null, $);
        },
        function ($, callback) {
            var table = $('#mw-pages').find('.mw-content-ltr table');
            var data = table.find('ul li').toArray()
                .map(function (li) {
                    var a = $(li).find('a');
                    return a.attr('title');
                })
                .filter(function (name) {
                    return !!name;
                });
            callback(null, data);
        },
        function (data, callback) {
            var keys = [name];
            h.saveData(dataDir, keys, {
                keys: keys,
                values: data.map(function (data) {
                    return [data];
                })
            }, callback);
        }
    ], callback)
}
747689
def download(url, target, headers=None, trackers=()):
    
    if headers is None:
        headers = {}
    headers.setdefault('user-agent', 'requests_download/'+__version__)
    r = requests.get(url, headers=headers, stream=True)
    r.raise_for_status()
    for t in trackers:
        t.on_start(r)


    with open(target, 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192):
            if chunk:
                f.write(chunk)
                for t in trackers:
                    t.on_chunk(chunk)

    for t in trackers:
        t.on_finish()
790139
def download(self, song):
		

		song_id = song['id']

		response = self._call(
			mm_calls.Export,
			self.uploader_id,
			song_id)
		audio = response.body
		suggested_filename = unquote(
			response.headers['Content-Disposition'].split("filename*=UTF-8''")[-1]
		)

		return (audio, suggested_filename)
817031
def parse_url(track_url):
    
    global arguments
    item = get_item(track_url)
    logger.debug(item)
    if not item:
        return
    elif item['kind'] == 'track':
        logger.info('Found a track')
        download_track(item)
    elif item['kind'] == 'playlist':
        logger.info('Found a playlist')
        download_playlist(item)
    elif item['kind'] == 'user':
        logger.info('Found a user profile')
        if arguments['-f']:
            download(item, 'favorites', 'likes')
        elif arguments['-C']:
            download(item, 'commented', 'commented tracks')
        elif arguments['-t']:
            download(item, 'tracks', 'uploaded tracks')
        elif arguments['-a']:
            download(item, 'all', 'tracks and reposts')
        elif arguments['-p']:
            download(item, 'playlists', 'playlists')
        elif arguments['-m']:
            download(item, 'playlists-liked', 'my and liked playlists')
        else:
            logger.error('Please provide a download type...')
    else:
        logger.error('Unknown item type {0}'.format(item['kind']))
255529
def download_tagged(self, profile: Profile, fast_update: bool = False,
                        target: Optional[str] = None,
                        post_filter: Optional[Callable[[Post], bool]] = None) -> None:
        """"""
        if target is None:
            target = profile.username + '/:tagged'
        self.context.log("Retrieving tagged posts for profile {}.".format(profile.username))
        count = 1
        for post in profile.get_tagged_posts():
            self.context.log("[%3i/???] " % (count), end="", flush=True)
            count += 1
            if post_filter is not None and not post_filter(post):
                self.context.log('<{} skipped>'.format(post))
            with self.context.error_catcher('Download tagged {}'.format(profile.username)):
                downloaded = self.download_post(post, target)
                if fast_update and not downloaded:
                    break
355050
def downloads(request):
    '''
    
    '''
    all_metadata = sorted(db.metadata.find(), key=lambda x: x['name'])
    return render(request, 'billy/web/public/downloads.html',
                  {'all_metadata': all_metadata})
483966
def playlist(self, playlist_id):
        '''
        
        '''
        playlist = self.connection.request(
            'getPlaylistByID',
            {'playlistID': playlist_id},
            self.connection.header('getPlaylistByID'))[1]
        return self._parse_playlist(playlist)
1304863
def download_track(track, playlist_name=None, playlist_file=None):
    
    global arguments

    title = track['title']
    title = title.encode('utf-8', 'ignore').decode('utf8')
    logger.info('Downloading {0}'.format(title))

    # Not streamable
    if not track['streamable']:
        logger.error('{0} is not streamable...'.format(title))
        return

    r = None
    # Downloadable track
    if track['downloadable'] and not arguments['--onlymp3']:
        logger.info('Downloading the original file.')
        original_url = track['download_url']
        r = requests.get(
            original_url, params={'client_id': CLIENT_ID}, stream=True
        )
        if r.status_code == 401:
            logger.info('The original file has no download left.')
            filename = get_filename(track)
        else:
            d = r.headers.get('content-disposition')
            filename = re.findall("filename=(.+)", d)[0][1:-1]
            filename = get_filename(track, filename)

    else:
        filename = get_filename(track)
    logger.debug("filename : {0}".format(filename))

    # Skip if file ID or filename already exists
    if already_downloaded(track, title, filename):
        return

    # Add the track to the generated m3u playlist file
    if playlist_file:
        duration = math.floor(track['duration'] / 1000)
        playlist_file.write(
            '#EXTINF:{0},{1}{3}{2}{3}'.format(
                duration, title, filename, os.linesep
            )
        )

    if arguments['--remove']:
        fileToKeep.append(filename)

    # Streamable track download
    if r is None or r.status_code == 401:
        url = track['stream_url']
        r = requests.get(url, params={'client_id': CLIENT_ID}, stream=True)
        logger.debug(r.url)
        if r.status_code == 401 or r.status_code == 429:
            r = requests.get(
                url, params={'client_id': ALT_CLIENT_ID}, stream=True
            )
            logger.debug(r.url)
            r.raise_for_status()
    temp = tempfile.NamedTemporaryFile(delete=False)

    total_length = int(r.headers.get('content-length'))

    min_size = arguments.get('--min-size')
    max_size = arguments.get('--max-size')

    if min_size is not None and total_length < min_size:
        logging.info('{0} not large enough, skipping'.format(title))
        return

    if max_size is not None and total_length > max_size:
        logging.info('{0} too large, skipping'.format(title))
        return

    received=0
    with temp as f:
        for chunk in progress.bar(
            r.iter_content(chunk_size=1024),
            expected_size=(total_length/1024) + 1,
            hide=True if arguments["--hide-progress"] else False
        ):
            if chunk:
                received+=len(chunk)
                f.write(chunk)
                f.flush()

    if received != total_length:
        logger.error('connection closed prematurely, download incomplete')
        sys.exit()

    shutil.move(temp.name, os.path.join(os.getcwd(), filename))
    if arguments['--flac'] and can_convert(filename):
        logger.info('Converting to .flac...')
        newfilename = filename[:-4] + ".flac"
        new = shlex.quote(newfilename)
        old = shlex.quote(filename)
        logger.debug("ffmpeg -i {0} {1} -loglevel fatal".format(old, new))
        os.system("ffmpeg -i {0} {1} -loglevel fatal".format(old, new))
        os.remove(filename)
        filename = newfilename

    if filename.endswith('.mp3') or filename.endswith('.flac'):
        try:
            set_metadata(track, filename, playlist_name)
        except Exception as e:
            logger.error('Error trying to set the tags...')
            logger.debug(e)
    else:
        logger.error("This type of audio doesn't support tagging...")

    # Try to change the real creation date
    created_at = track['created_at']
    timestamp = datetime.strptime(created_at, '%Y/%m/%d %H:%M:%S %z')
    filetime = int(time.mktime(timestamp.timetuple()))
    try_utime(filename, filetime)

    logger.info('{0} Downloaded.\n'.format(filename))
    record_download_archive(track)
131899
def collection(self, user_id):
        
        # TODO further evaluation of the page param, I don't know where the
        # limit is.
        dct = {'userID': user_id, 'page': 0}
        r = 'userGetSongsInLibrary'
        result = self.connection.request(r, dct, self.connection.header(r))
        songs = result[1]['Songs']
        return [Song.from_response(song, self.connection) for song in songs]
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('..')
980594
def download(self, days=60):
        
        days_ago = datetime.datetime.now() - datetime.timedelta(days=days)
        as_of = time.strftime("%Y%m%d", days_ago.timetuple())
        query = self._download_query(as_of=as_of)
        response = self.institution.client().post(query)
        return StringIO(response)
646005
def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool:
        
        service = self.__get_service()
        request = service.files().get_media(fileId=item_id)
        self.__create_download_dir(dir_name)
        fh = io.FileIO(os.path.join(dir_name, item_name), mode='wb')
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()

        return done
1183713
def download_user_playlists_by_search(self, user_name):
        

        try:
            user = self.crawler.search_user(user_name, self.quiet)
        except RequestException as exception:
            click.echo(exception)
        else:
            self.download_user_playlists_by_id(user.user_id)
569207
def download_sdk(url):
    """"""
    r = requests.get(url)
    r.raise_for_status()
    return StringIO(r.content)
952616
def playlist(self, playlist_id, *, include_songs=False):
		

		playlist_info = next(
			(
				playlist
				for playlist in self.playlists(include_songs=include_songs)
				if playlist['id'] == playlist_id
			),
			None
		)

		return playlist_info