Ejemplo n.º 1
0
    def remove_torrent(self, ihash, del_files=False):
        # this feels redundant. the torrent will stop the download itself,
        # can't we accomplish the rest through a callback or something?
        if self.torrent_running(ihash):
            self.stop_torrent(ihash)

        t = self.torrents[ihash]

        # super carefully determine whether these are really incomplete files
        fs_save_incomplete_in, junk = encode_for_filesystem(
            self.config['save_incomplete_in']
            )
        inco = ((not t.completed) and
                (t.working_path != t.destination_path) and
                t.working_path.startswith(fs_save_incomplete_in))
        del_files = del_files and inco

        df = t.shutdown()

        df.addCallback(lambda *args: t.remove_state_files(del_files=del_files))

        if ihash in self.running:
            del self.running[ihash]

        # give the torrent a blank feedback, so post-mortem errors don't
        # confuse multitorrent
        t.feedback = Feedback()
        del self.torrents[ihash]
        if self.resume_from_torrent_config:
            self._dump_torrents()

        return df
    def _to_fs_2(self, name):
        if sys.platform.startswith('win'):
            name, bad = self._fix_windows(name)

        r, bad = encode_for_filesystem(name)
        self.bad_conversion = bad

        return (bad, r)
Ejemplo n.º 3
0
    def _read_torrent_config(self, infohash):
        path = os.path.join(self.data_dir, 'torrents', infohash.encode('hex'))
        if not os.path.exists(path):
            raise BTFailure,_("Coult not open the torrent config: " + infohash.encode('hex'))
        f = file(path, 'rb')
        data = f.read()
        f.close()
        try:
            torrent_config = cPickle.loads(data)
        except:
            # backward compatibility with <= 4.9.3
            torrent_config = bdecode(data)
            for k, v in torrent_config.iteritems():
                try:
                    torrent_config[k] = v.decode('utf8')
                    if k in ('destination_path', 'working_path'):
                        torrent_config[k] = encode_for_filesystem(torrent_config[k])[0]
                except:
                    pass
        if not torrent_config.get('destination_path'):
            raise BTFailure( _("Invalid torrent config file"))
        if not torrent_config.get('working_path'):
            raise BTFailure( _("Invalid torrent config file"))

        if get_filesystem_encoding() == None:
            # These paths should both be unicode.  If they aren't, they are the
            # broken product of some old version, and probably are in the
            # encoding we used to use in config files.  Attempt to recover.
            dp = torrent_config['destination_path']
            if isinstance(dp, str):
                try:
                    dp = dp.decode(old_broken_config_subencoding)
                    torrent_config['destination_path'] = dp
                except:
                    raise BTFailure( _("Invalid torrent config file"))

            wp = torrent_config['working_path']
            if isinstance(wp, str):
                try:
                    wp = wp.decode(old_broken_config_subencoding)
                    torrent_config['working_path'] = wp
                except:
                    raise BTFailure( _("Invalid torrent config file"))

        return torrent_config
            sys.exit(1)

        # Modifying default values from get_defaults is annoying...
        # Implementing specific default values for each uiname in
        # defaultargs.py is even more annoying.  --Dave
        ddir = os.path.join(platform.get_dot_dir(), "launchmany-curses")
        ddir = decode_from_filesystem(ddir)
        modify_default(defaults, "data_dir", ddir)
        config, args = configfile.parse_configuration_and_args(defaults, uiname, sys.argv[1:], 0, 1)

        if args:
            torrent_dir = args[0]
            config["torrent_dir"] = platform.decode_from_filesystem(torrent_dir)
        else:
            torrent_dir = config["torrent_dir"]
            torrent_dir, bad = platform.encode_for_filesystem(torrent_dir)
            if bad:
                raise BTFailure(_("Warning: ") + config["torrent_dir"] + _(" is not a directory"))

        if not os.path.isdir(torrent_dir):
            raise BTFailure(_("Warning: ") + torrent_dir + _(" is not a directory"))

        # the default behavior is to save_in files to the platform
        # get_save_dir.  For launchmany, if no command-line argument
        # changed the save directory then use the torrent directory.
        if config["save_in"] == platform.get_save_dir():
            config["save_in"] = config["torrent_dir"]

    except BTFailure, e:
        print _("error: ") + unicode(e.args[0]) + _("\nrun with no args for parameter explanations")
        sys.exit(1)
Ejemplo n.º 5
0
             self.total_downmeasure, self.filepool, self.dht, self,
             self.log_root)
 t.metainfo.reported_errors = True # suppress redisplay on restart
 if infohash != t.metainfo.infohash:
     self.logger.error((_("Corrupt data in \"%s\", cannot restore torrent.") % hashtext) +
                       _("(infohash mismatch)"))
     return None
 if len(line) == 41:
     t.working_path = None
     t.destination_path = None
     return infohash, t
 try:
     if version < 2:
         t.working_path = line[41:-1].decode('string_escape')
         t.working_path = t.working_path.decode('utf-8')
         t.working_path = encode_for_filesystem(t.working_path)[0]
         t.destination_path = t.working_path
     elif version == 3:
         up, down, working_path = line[41:-1].split(' ', 2)
         t.uptotal = t.uptotal_old = int(up)
         t.downtotal = t.downtotal_old = int(down)
         t.working_path = working_path.decode('string_escape')
         t.working_path = t.working_path.decode('utf-8')
         t.working_path = encode_for_filesystem(t.working_path)[0]
         t.destination_path = t.working_path
     elif version >= 4:
         up, down = line[41:-1].split(' ', 1)
         t.uptotal = t.uptotal_old = int(up)
         t.downtotal = t.downtotal_old = int(down)
 except ValueError:  # unpack, int(), decode()
     raise BTFailure(_("Invalid state file (bad entry)"))
Ejemplo n.º 6
0
 def __init__(self, *args):
     IPCSocketBase.__init__(self, *args)
     data_dir,bad = encode_for_filesystem(self.config['data_dir'])
     if bad:
         raise BTFailure(_("Invalid path encoding."))
     self.socket_filename = os.path.join(data_dir, self.name)
Ejemplo n.º 7
0
def parse_configuration_and_args(defaults, uiname, arglist=[], minargs=None,
                                 maxargs=None):
    """Given the default option settings and overrides these defaults
       from values read from the config file, and again overrides the
       config file with the arguments that appear in the arglist.

       'defaults' is a list of tuples of the form (optname, value,
       desc) where 'optname' is a string containing the option's name,
       value is the option's default value, and desc is the option's
       description.

       'uiname' is a string specifying the user interface that has been
       created by the caller.  Ex: bittorrent, maketorrent.

       arglist is usually argv[1:], i.e., excluding the name used to
       execute the program.

       minargs specifies the minimum number of arguments that must appear in
       arglist.  If the number of arguments is less than the minimum then
       a BTFailure exception is raised.

       maxargs specifies the maximum number of arguments that can appear
       in arglist.  If the number of arguments exceeds the maximum then
       a BTFailure exception is raised.

       This returns the tuple (config,args) where config is
       a dictionary of (option, value) pairs, and args is the list
       of arguments in arglist after the command-line arguments have
       been removed.

       For example:

          bittorrent-curses.py --save_as lx-2.6.rpm lx-2.6.rpm.torrent --max_upload_rate 0

          returns a (config,args) pair where the
          config dictionary contains many defaults plus
          the mappings
            'save_as': 'linux-2.6.15.tar.gz'
          and
            'max_upload_rate': 0

          The args in the returned pair is
            args= ['linux-2.6.15.tar.gz.torrent']
    """
    assert type(defaults)==list
    assert type(uiname)==str
    assert type(arglist)==list
    assert minargs is None or type(minargs) in (int,long) and minargs>=0
    assert maxargs is None or type(maxargs) in (int,long) and maxargs>=minargs

    # remap shortform arguments to their long-forms.
    arglist = convert_from_shortforms(arglist)

    defconfig = dict([(name, value) for (name, value, doc) in defaults])
    if arglist[0:] == ['--version']:
        print version
        sys.exit(0)

    if arglist[0:] in (['--help'], ['-h'], ['--usage'], ['-?']):
        parseargs.printHelp(uiname, defaults)
        sys.exit(0)

    if "--use_factory_defaults" not in arglist:
        presets = get_config(defconfig, uiname)

    # run as if fresh install using temporary directories.
    else:
        presets = {}
        temp_dir = get_temp_subdir()
        #set_config_dir(temp_dir)  # is already set in platform.py.
        save_in = encode_for_filesystem( u"save_in" )[0]
        presets["save_in"] = \
            decode_from_filesystem(os.path.join(temp_dir,save_in))
        data = encode_for_filesystem( u"data" )[0]
        presets["data_dir"] = \
            decode_from_filesystem(os.path.join(temp_dir,data))
        incomplete = encode_for_filesystem( u"incomplete" )[0]
        presets["save_incomplete_in"] = \
            decode_from_filesystem(os.path.join(temp_dir,incomplete))
        presets["one_connection_per_ip"] = False

    config = args = None
    try:
        config, args = parseargs.parseargs(arglist, defaults, minargs, maxargs,
                                           presets)
    except parseargs.UsageException, e:
        print e
        parseargs.printHelp(uiname, defaults)
        sys.exit(0)
Ejemplo n.º 8
0
        presets["one_connection_per_ip"] = False

    config = args = None
    try:
        config, args = parseargs.parseargs(arglist, defaults, minargs, maxargs,
                                           presets)
    except parseargs.UsageException, e:
        print e
        parseargs.printHelp(uiname, defaults)
        sys.exit(0)

    datadir = config.get('data_dir')
    found_4x_config = False

    if datadir:
        datadir,bad = encode_for_filesystem(datadir)
        if bad:
            raise BTFailure(_("Invalid path encoding."))
        if not os.path.exists(datadir):
            os.mkdir(datadir)
        if uiname in ('bittorrent', 'maketorrent'):
            values = {}

            p = _read_config(os.path.join(datadir, MAIN_CONFIG_FILE))

            if p.has_section('format'):
                encoding = p.get('format', 'encoding')
            else:
                encoding = old_broken_config_subencoding

            if not p.has_section(uiname) and p.has_section(alt_uiname[uiname]):
        if available_version <= self.current_version:
            self.debug(debug_prefix + 'not updating old version %s' %
                       str(available_version))
            self._restart()
            return

        if not self._can_install():
            self.debug(debug_prefix + 'cannot install on this os')
            self.available_version = available_version
            self._restart()
            return

        installer_name = self._calc_installer_name(available_version)
        installer_url  = self.version_site + installer_name + '.torrent'

        fs_name = encode_for_filesystem(installer_name.decode('ascii'))[0]
        installer_path = os.path.join(self.installer_dir, fs_name)

        df = ThreadedDeferred(_wrap_task(self.rawserver.external_add_task),
                              self._get_torrent, installer_url)
        yield df
        torrentfile = df.getResult()

        df = ThreadedDeferred(_wrap_task(self.rawserver.external_add_task),
                              self._get_signature, installer_url)
        yield df
        signature = df.getResult()

        if torrentfile and signature:
            df = ThreadedDeferred(_wrap_task(self.rawserver.external_add_task),
                                  self._check_signature, torrentfile, signature)