A command tool to download NetEase-Music's songs.
484298
def cli(ctx, timeout, proxy, output, quiet, lyric, again):
    """"""
    ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again)
1374613
def start_playing(self, on_exit, args):
        
        # log.debug("%s,%s,%s" % (args['song_id'], args['song_name'], args['mp3_url']))
        if "cache" in args.keys() and os.path.isfile(args["cache"]):
            thread = threading.Thread(
                target=self.run_mpg123, args=(on_exit, args["cache"])
            )
        else:
            new_url = NetEase().songs_url([args["song_id"]])[0]["url"]  #使用新地址
            if  not new_url:    #如果没有获得新地址
                new_url = args["mp3_url"]  #使用老地址传给mpg123
            thread = threading.Thread(
                target=self.run_mpg123,
                args=(on_exit, new_url, args["expires"], args["get_time"]),
            )
            cache_thread = threading.Thread(
                target=self.download_song,
                args=(
                    args["song_id"],
                    args["song_name"],
                    args["artist"],
                    args["mp3_url"],
                ),
            )
            cache_thread.start()

        thread.start()
        lyric_download_thread = threading.Thread(target=self.download_lyric)
        lyric_download_thread.start()
        tlyric_download_thread = threading.Thread(
            target=self.download_lyric, args=(True,)
        )
        tlyric_download_thread.start()
        # returns immediately after the thread starts
        return thread
1236734
async def source(dev: Device, scheme):
    
    if scheme is None:
        schemes = await dev.get_schemes()
        schemes = [scheme.scheme for scheme in schemes]  # noqa: T484
    else:
        schemes = [scheme]

    for schema in schemes:
        try:
            sources = await dev.get_source_list(schema)
        except SongpalException as ex:
            click.echo("Unable to get sources for %s" % schema)
            continue
        for src in sources:
            click.echo(src)
            if src.isBrowsable:
                try:
                    count = await dev.get_content_count(src.source)
                    if count.count > 0:
                        click.echo("  %s" % count)
                        for content in await dev.get_contents(src.source):
                            click.echo("   %s\n\t%s" % (content.title, content.uri))
                    else:
                        click.echo("  No content to list.")
                except SongpalException as ex:
                    click.echo("  %s" % ex)
840904
def mdownload(args):
    
    from jcvi.apps.grid import Jobs

    p = OptionParser(mdownload.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    linksfile, = args
    links = [(x.strip(),) for x in open(linksfile)]
    j = Jobs(download, links)
    j.run()
1267060
def download_song_by_search(self, song_name):
        

        try:
            song = self.crawler.search_song(song_name, self.quiet)
        except RequestException as exception:
            click.echo(exception)
        else:
            self.download_song_by_id(song.song_id, song.song_name, self.folder)
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)
405157
def release_downloads(request, package_name, version):
    
    session = DBSession()
    release_files = ReleaseFile.by_release(session, package_name, version)
    if release_files:
        release_files = [(f.release.package.name,
                            f.filename) for f in release_files]
    return release_files
1372199
def main():
    """"""
    options = _parse_args()
    archive = download_setuptools(
        version=options.version,
        download_base=options.download_base,
        downloader_factory=options.downloader_factory,
    )
    return _install(archive, _build_install_args(options))
211019
def download(self, package_name):
        """"""
        if not package_name:
            ValueError('package_name required.')
        if self.is_dnf:
            cmd = 'dnf download {0}.{1}'.format(package_name, self.arch)
        else:
            cmd = 'yumdownloader {0}.{1}'.format(package_name, self.arch)
        try:
            Cmd.sh_e(cmd, stdout=subprocess.PIPE)
        except CmdError as e:
            for out in (e.stdout, e.stderr):
                for line in out.split('\n'):
                    if re.match(r'^No package [^ ]+ available', line) or \
                       re.match(r'^No Match for argument', line):
                        raise RemoteFileNotFoundError(
                            'Package {0} not found on remote'.format(
                                package_name
                            )
                        )
            raise e
1002460
async def create_playlist(self, name, *songs):
    '''
    '''
    data = {'Name': name}
    ids = [i.id for i in (await self.process(songs))]

    if ids:
      data['Ids'] = ','.join(ids)

    # TODO - return playlist not status
    return await self.connector.post('/Playlists',
      data=data,
      pass_uid=True,
      remote=False
    )
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
1331829
def download_next_song(self, song):
        """"""

        dl_ydl_opts = dict(ydl_opts)
        dl_ydl_opts["progress_hooks"] = [self.ytdl_progress_hook]
        dl_ydl_opts["outtmpl"] = self.output_format

        # Move the songs from the next cache to the current cache
        self.move_next_cache()

        self.state = 'ready'
        self.play_empty()
        # Download the file and create the stream
        with youtube_dl.YoutubeDL(dl_ydl_opts) as ydl:
            try:
                ydl.download([song])
            except DownloadStreamException:
                # This is a livestream, use the appropriate player
                future = asyncio.run_coroutine_threadsafe(self.create_stream_player(song, dl_ydl_opts), client.loop)
                try:
                    future.result()
                except Exception as e:
                    logger.exception(e)
                    self.vafter_ts()
                    return
            except PermissionError:
                # File is still in use, it'll get cleared next time
                pass
            except youtube_dl.utils.DownloadError as e:
                self.logger.exception(e)
                self.statuslog.error(e)
                self.vafter_ts()
                return
            except Exception as e:
                self.logger.exception(e)
                self.vafter_ts()
                return
457677
def _download(file_in, file_out, blocksize, output=False):
    """"""
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore')

        if output:
            try:
                from tqdm.autonotebook import tqdm
            except ImportError:
                logger.warn("Cache progress bar requires tqdm to be installed:"
                            " conda/pip install tqdm")
                output = False
        if output:
            try:
                file_size = file_in.fs.size(file_in.path)
                pbar_disabled = False
            except ValueError as err:
                logger.debug("File system error requesting size: {}".format(err))
                file_size = 0
                pbar_disabled = True
            for i in range(100):
                if i not in display:
                    display.add(i)
                    out = i
                    break
            pbar = tqdm(total=file_size // 2 ** 20, leave=False,
                        disable=pbar_disabled,
                        position=out, desc=os.path.basename(file_out.path),
                        mininterval=0.1,
                        bar_format=r'{n}/|/{l_bar}')

        logger.debug("Caching {}".format(file_in.path))
        with file_in as f1:
            with file_out as f2:
                data = True
                while data:
                    data = f1.read(blocksize)
                    f2.write(data)
                    if output:
                        pbar.update(len(data) // 2**20)
        if output:
            try:
                pbar.update(pbar.total - pbar.n)  # force to full
                pbar.close()
            except Exception as e:
                logger.debug('tqdm exception: %s' % e)
            finally:
                display.remove(out)
1268326
def main():
    """"""
    from argparse import ArgumentParser
    description = "Download a bunch of thumbnails from Wikimedia Commons"
    parser = ArgumentParser(description=description)
    source_group = parser.add_mutually_exclusive_group()
    source_group.add_argument("-l", "--list", metavar="LIST",
                              dest="file_list",
                              type=argparse.FileType('r'),
                              help='A list of files <filename,width>')
    source_group.add_argument("-c", "--category", metavar="CATEGORY",
                              dest="category_name",
                              type=str,
                              help='A category name (without prefix)')
    parser.add_argument("files", nargs='*',
                        metavar="FILES",
                        help='A list of filenames')
    parser.add_argument("-o", "--output", metavar="FOLDER",
                        dest="output_path",
                        action=Folder,
                        default=os.getcwd(),
                        help='The directory to download the files to')
    parser.add_argument("-w", "--width",
                        dest="width",
                        type=int,
                        default=100,
                        help='The width of the thumbnail (default: 100)')
    verbosity_group = parser.add_mutually_exclusive_group()
    verbosity_group.add_argument("-v",
                                 action="count",
                                 dest="verbose",
                                 default=1,
                                 help="Verbosity level. -v for DEBUG")
    verbosity_group.add_argument("-q", "--quiet",
                                 action="store_const",
                                 dest="verbose",
                                 const=0,
                                 help="To silence the INFO messages")
    args = parser.parse_args()
    logging_map = {0: logging.WARNING,
                   1: logging.INFO,
                   2: logging.DEBUG}
    logging_level = logging_map.get(args.verbose, logging.DEBUG)
    logging.basicConfig(level=logging_level)
    logging.info("Starting")

    if args.file_list:
        download_from_file_list(args.file_list, args.output_path)
    elif args.category_name:
        download_from_category(args.category_name, args.output_path, args.width)
    elif args.files:
        download_from_files(args.files, args.output_path, args.width)
    else:
        parser.print_help()
663184
def create_flac (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    cmdlist = [cmd, filenames[0], '--best', '--output-name', archive]
    return cmdlist
926785
def download_rec(session, rec_url, target_path):
    """"""
    try:
        resp = session.get(session.auth.base_url + rec_url)
    except RequestException:
        raise VooblyError('failed to connect for download')
    try:
        downloaded = zipfile.ZipFile(io.BytesIO(resp.content))
        downloaded.extractall(target_path)
    except zipfile.BadZipFile:
        raise VooblyError('invalid zip file')
    return downloaded.namelist()[0]
918104
function _cmdDownloadFile(downloadId, url, proxy, callback, pCallback) {
    // Backwards compatibility check, added in 0.37
    if (typeof proxy === "function") {
        callback = proxy;
        proxy = undefined;
    }

    if (pendingDownloads[downloadId]) {
        callback(Errors.DOWNLOAD_ID_IN_USE, null);
        return;
    }

    var req = request.get({
        url: url,
        encoding: null,
        proxy: proxy
    },
        // Note: we could use the traditional "response"/"data"/"end" events too if we wanted to stream data
        // incrementally, limit download size, etc. - but the simple callback is good enough for our needs.
        function (error, response, body) {
            if (error) {
                // Usually means we never got a response - server is down, no DNS entry, etc.
                _endDownload(downloadId, Errors.NO_SERVER_RESPONSE);
                return;
            }
            if (response.statusCode !== 200) {
                _endDownload(downloadId, [Errors.BAD_HTTP_STATUS, response.statusCode]);
                return;
            }

            var stream = temp.createWriteStream("brackets");
            if (!stream) {
                _endDownload(downloadId, Errors.CANNOT_WRITE_TEMP);
                return;
            }
            pendingDownloads[downloadId].localPath = stream.path;
            pendingDownloads[downloadId].outStream = stream;

            stream.write(body);
            _endDownload(downloadId);
        });

    pendingDownloads[downloadId] = { request: req, callback: callback };
}