Search and download torrents until the user says it so.
321698
def run_it():
    """"""
    initialize()
    parser = get_parser()
    args = None
    first_parse = True
    while(True):
        if first_parse is True:
            first_parse = False
            args = parser.parse_args()
        else:
            print(textwrap.dedent(
                '''\
                Search again like in the beginning.
                  -- You can either choose best rated or list mode.
                  -- This time, you can insert the search string without double quotes.
                  Remember the list mode options!
                    0: torrent project.
                    1: the pirate bay.
                    2: 1337x.
                    3: eztv.
                    4: limetorrents.
                    5: isohunt.
                '''))

            print('Or.. if you want to exit just write "' +
                  Colors.LRED + 'Q' + Colors.ENDC + '" or "' +
                  Colors.LRED + 'q' + Colors.ENDC + '".')
            input_parse = input('>> ').replace("'", "").replace('"', '')
            if input_parse in ['Q', 'q']:
                sys.exit(1)

            args = parser.parse_args(input_parse.split(' ', 2))

        if args.str_search.strip() == "":
            print('Please insert an appropiate non-empty string.')
        else:
            auto = AutoPy(*insert(args))
            auto.get_content()
            auto.select_torrent()
            auto.download_torrent()
275222
def create(source, dest, tracker, open_trackers, comment, cache):
    """"""

    source_title = path.basename(source).replace('.', '_').replace(' ', '_')
    dest = '%s.torrent' % path.join(dest, source_title)

    click.secho('Creating torrent from %s ...' % source)

    my_torrent = Torrent.create_from(source)

    if comment:
        my_torrent.comment = comment

    urls = []

    if tracker:
        urls = tracker.split(',')

    if open_trackers:
        click.secho('Fetching an up-to-date open tracker list ...')
        try:
            urls.extend(get_open_trackers_from_remote())
        except RemoteDownloadError:
            click.secho('Failed. Using built-in open tracker list.', fg='red', err=True)
            urls.extend(get_open_trackers_from_local())

    if urls:
        my_torrent.announce_urls = urls

    my_torrent.to_file(dest)

    click.secho('Torrent file created: %s' % dest, fg='green')
    click.secho('Torrent info hash: %s' % my_torrent.info_hash, fg='blue')

    if cache:
        click.secho('Uploading to %s torrent cache service ...')
        try:
            result = upload_to_cache_server(dest)
            click.secho('Cached torrent URL: %s' % result, fg='yellow')

        except RemoteUploadError as e:
            click.secho('Failed: %s' % e, fg='red', err=True)
523918
def info(torrent_path):
    """"""

    my_torrent = Torrent.from_file(torrent_path)

    size = my_torrent.total_size

    click.secho('Name: %s' % my_torrent.name, fg='blue')
    click.secho('Files:')
    for file_tuple in my_torrent.files:
        click.secho(file_tuple.name)

    click.secho('Hash: %s' % my_torrent.info_hash, fg='blue')
    click.secho('Size: %s (%s)' % (humanize_filesize(size), size), fg='blue')
    click.secho('Magnet: %s' % my_torrent.get_magnet(), fg='yellow')
342651
def download(self, url, dst, timeout=None):
        
        response = self.get_response(url, timeout=timeout)
        if response:
            with open(dst, "wb") as f:
                for block in response.iter_content(1024):
                    if not block:
                        break
                    f.write(block)
227737
def items(self):
        
        if self._multipage:
            while True:
                # Pool for more torrents
                items = super(Paginated, self).items()
                # Stop if no more torrents
                first = next(items, None)
                if first is None:
                    raise StopIteration()
                # Yield them if not
                else:
                    yield first
                    for item in items:
                        yield item
                # Go to the next page
                self.next()
        else:
            for item in super(Paginated, self).items():
                yield item
305904
def fetch(self):
        """"""
        self.content = self.client.get_content(
            uri=self.uri
        )
        self.hash = hashlib.sha256(
            self.content
        ).hexdigest()
1211990
def start(self):
        """"""
        self._lc = LoopingCall(self._download)
        # Run immediately, and then every 30 seconds:
        self._lc.start(30, now=True)
108543
public static TrackedTorrent load(File torrent) throws IOException {

    TorrentMetadata torrentMetadata = new TorrentParser().parseFromFile(torrent);
    return new TrackedTorrent(torrentMetadata.getInfoHash());
  }
852216
def _download(self, force_overwrite=False, verbose=False):
        
        if not force_overwrite:
            # If the file is already there, we're done
            if os.path.isfile(self.filepath):
                if verbose:
                    print(
                        "File already available at %s -- skipping"
                        % (self.filepath)
                    )
                return False
        stream_download(self.URL, self.filepath, verbose=verbose)
        return True
568535
def maybe_download_and_extract():
  """"""
  dest_directory = "/tmp/cifar"
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename,
          float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
    tarfile.open(filepath, 'r:gz').extractall(dest_directory)
575133
def download(self, force=False, silent=False):
        """"""
        def _download():
            if self.url.startswith("http"):
                self._download_http(silent=silent)
            elif self.url.startswith("ftp"):
                self._download_ftp(silent=silent)
            else:
                raise ValueError("Invalid URL %s" % self.url)
            logger.debug("Moving %s to %s" % (
                self._temp_file_name,
                self.destination))
            shutil.move(self._temp_file_name, self.destination)
            logger.debug("Successfully downloaded %s" % self.url)

        try:
            is_already_downloaded = os.path.isfile(self.destination)
            if is_already_downloaded:
                if force:
                    try:
                        os.remove(self.destination)
                    except Exception:
                        logger.error("Cannot delete %s" % self.destination)
                    logger.info(
                        "Downloading %s to %s" % (self.url, self.destination))
                    logger.debug(
                        "Downloading %s to %s" % (self.url,
                                                  self._temp_file_name))
                    _download()
                else:
                    logger.info(("File %s already exist. Use force=True if you"
                                 " would like to overwrite it.") %
                                self.destination)
            else:
                _download()
        finally:
            try:
                os.remove(self._temp_file_name)
            except OSError:
                pass
328437
def fetch(
            self,
            url,
            filename=None,
            decompress=False,
            force=False,
            timeout=None,
            use_wget_if_available=True):
        
        key = (url, decompress)
        if not force and key in self._local_paths:
            path = self._local_paths[key]
            if exists(path):
                return path
            else:
                del self._local_paths[key]
        path = download.fetch_file(
            url,
            filename=filename,
            decompress=decompress,
            subdir=self.subdir,
            force=force,
            timeout=timeout,
            use_wget_if_available=use_wget_if_available)

        self._local_paths[key] = path
        return path
804535
def download(url, dest):
    """"""
    path = os.path.join(dest, url.split('/')[-1])
    r = requests.get(url, stream=True)
    r.raise_for_status()
    with open(path, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    return path
598972
def _get_torrent(self, row):
        
        td = row("td")
        name = td("a.cellMainLink").text()
        name = name.replace(" . ", ".").replace(" .", ".")
        author = td("a.plain").text()
        verified_author = True if td(".lightgrey>.ka-verify") else False
        category = td("span").find("strong").find("a").eq(0).text()
        verified_torrent = True if td(".icon16>.ka-green") else False
        comments = td(".iaconbox>.icommentjs>.iconvalue").text()
        torrent_link = "http://" + BASE.domain
        if td("a.cellMainLink").attr("href") is not None:
            torrent_link += td("a.cellMainLink").attr("href")
        magnet_link = td("a[data-nop]").eq(1).attr("href")
        download_link = td("a[data-download]").attr("href")

        td_centers = row("td.center")
        size = td_centers.eq(0).text()
        files = td_centers.eq(1).text()
        age = " ".join(td_centers.eq(2).text().split())
        seed = td_centers.eq(3).text()
        leech = td_centers.eq(4).text()

        return Torrent(name, author, verified_author, category, size,
                       files, age, seed, leech, verified_torrent, comments,
                       torrent_link, magnet_link, download_link)
15183
def download(url, dest):
    
    u = urllib.FancyURLopener()
    logger.info("Downloading %s..." % url)
    u.retrieve(url, dest)
    logger.info('Done, see %s' % dest)
    return dest
898517
def idle_task(self):
        ''''''
        if self.downloaders_lock.acquire(False):
            removed_one = False
            for url in self.downloaders.keys():
                if not self.downloaders[url].is_alive():
                    print("fw: Download thread for (%s) done" % url)
                    del self.downloaders[url]
                    removed_one = True
            if removed_one and not self.downloaders.keys():
                # all downloads finished - parse them
                self.manifests_parse()

            self.downloaders_lock.release()
1366828
def do_session(self):
        """"""
        def filenames():
            'Helper'
            for arg in self.args:
                if os.path.isdir(arg):
                    for name in glob.glob(os.path.join(arg, '*.torrent.rtorrent')):
                        yield name
                elif arg == '@-':
                    for line in sys.stdin.read().splitlines():
                        if line.strip():
                            yield line.strip()
                elif arg.startswith('@'):
                    if not os.path.isfile(arg[1:]):
                        self.parser.error("File not found (or not a file): {}".format(arg[1:]))
                    with io.open(arg[1:], encoding='utf-8') as handle:
                        for line in handle:
                            if line.strip():
                                yield line.strip()
                else:
                    yield arg

        proxy = self.open()
        for filename in filenames():
            # Check filename and extract infohash
            self.LOG.debug("Reading '%s'...", filename)
            match = re.match(r'(?:.+?[-._])?([a-fA-F0-9]{40})(?:[-._].+?)?\.torrent\.rtorrent',
                             os.path.basename(filename))
            if not match:
                self.LOG.warn("Skipping badly named session file '%s'...", filename)
                continue
            infohash = match.group(1)

            # Read bencoded data
            try:
                with open(filename, 'rb') as handle:
                    raw_data = handle.read()
                data = Bunch(bencode.bdecode(raw_data))
            except EnvironmentError as exc:
                self.LOG.warn("Can't read '%s' (%s)" % (
                    filename, str(exc).replace(": '%s'" % filename, ""),
                ))
                continue

            ##print(infohash, '=', repr(data))
            if 'state_changed' not in data:
                self.LOG.warn("Skipping invalid session file '%s'...", filename)
                continue

            # Restore metadata
            was_active = proxy.d.is_active(infohash)
            proxy.d.ignore_commands.set(infohash, data.ignore_commands)
            proxy.d.priority.set(infohash, data.priority)

            if proxy.d.throttle_name(infohash) != data.throttle_name:
                proxy.d.pause(infohash)
                proxy.d.throttle_name.set(infohash, data.throttle_name)

            if proxy.d.directory(infohash) != data.directory:
                proxy.d.stop(infohash)
                proxy.d.directory_base.set(infohash, data.directory)

            for i in range(5):
                key = 'custom%d' % (i + 1)
                getattr(proxy.d, key).set(infohash, data[key])

            for key, val in data.custom.items():
                proxy.d.custom.set(infohash, key, val)

            for name in data.views:
                try:
                    proxy.view.set_visible(infohash, name)
                except xmlrpclib.Fault as exc:
                    if 'Could not find view' not in str(exc):
                        raise

            if was_active and not proxy.d.is_active(infohash):
                (proxy.d.resume if proxy.d.is_open(infohash) else proxy.d.start)(infohash)
            proxy.d.save_full_session(infohash)

            """ TODO:
                NO public "set" command! 'timestamp.finished': 1503012786,
                NO public "set" command! 'timestamp.started': 1503012784,
                NO public "set" command! 'total_uploaded': 0,
            """