def to_utf8(name):
     if isinstance(name, unicode):
         u = name
     else:
         try:
             u = decode_from_filesystem(name)
         except Exception, e:
             raise BTFailure(_('Could not convert file/directory name "%s" to '
                               'Unicode (%s). Either the assumed filesystem '
                               'encoding "%s" is wrong or the filename contains '
                               'illegal bytes.') % (name, unicode(e.args[0]), get_filesystem_encoding()))
def get_config(defaults, section):
    """This reads the key-value pairs from the specified section in the
       config file and from the common section.  It then places those
       appearing in the defaults into a dict, which is then returned.

       @type defaults: dict
       @param defaults: dict of name-value pairs derived from the
          defaults list for this application (see defaultargs.py).
       @type section: str
       @param section: in the configuration from which to read options.
          So far, the sections have been named after applications, e.g.,
          bittorrent, bittorrent-console, etc.
       @return: a dict containing option-value pairs.
       """
    assert type(defaults)==dict
    assert type(section)==str

    configdir = get_dot_dir()

    if configdir is None:
        return {}

    if not os.path.isdir(configdir):
        try:
            os.mkdir(configdir, 0700)
        except:
            pass

    p = _read_config(os.path.join(configdir, 'config'))  # returns parser.

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

    values = {}
    if p.has_section(section):
        for name, value in p.items(section):
            if name in defaults:
                values[name] = value
    if p.has_section('common'):
        for name, value in p.items('common'):
            if name in defaults and name not in values:
                values[name] = value
    if defaults.get('data_dir') == '' and \
           'data_dir' not in values and os.path.isdir(configdir):
        datadir = os.path.join(configdir, 'data')
        values['data_dir'] = decode_from_filesystem(datadir)

    parseargs.parse_options(defaults, values, encoding)
    return values
    return defaults_tuplelist


if __name__ == "__main__":
    uiname = "launchmany-curses"
    defaults = get_defaults(uiname)
    try:
        if len(sys.argv) < 2:
            printHelp(uiname, defaults)
            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"))
Beispiel #4
0
def expanduser(path):
    user_path = os.path.expanduser(path)
    print "expanduser: user_path=", user_path
    print "str?",  isinstance(user_path,str)
    print "unicode?", isinstance(user_path,unicode)
    return decode_from_filesystem(user_path)
Beispiel #5
0
def commonprefx(pathlist):
    fslist = [efs2(path) for path in pathlist]
    return decode_from_filesystem(os.path.commonprefix(fslist))
Beispiel #6
0
def realpath(path):
    fspath = efs2(path)
    return decode_from_filesystem(os.path.realpath(fspath))
Beispiel #7
0
def normpath(path):
    fspath = efs2(path)
    return decode_from_filesystem(os.path.normpath(fspath))
Beispiel #8
0
def basename(path):
    fspath = efs2(path)
    return decode_from_filesystem(os.path.basename(fspath))
Beispiel #9
0
def split(path):
    fspath, fsname = os.path.split(path)
    return decode_from_filesystem(fspath), decode_from_filesystem(fsname)
Beispiel #10
0
    defaults = get_defaults('bittorrent-tracker')   # hard-coded defaults.
    try:
        config, files = parse_configuration_and_args(defaults,
           'bittorrent-tracker', args, 0, 0 )
    except ValueError, e:
        print _("error: ") + unicode(e.args[0])
        print _("run with -? for parameter explanations")
        return
    except BTFailure, e:
        print _("error: ") + unicode(e.args[0])
        print _("run with -? for parameter explanations")
        return

    if config['dfile']=="":
        config['dfile'] = decode_from_filesystem(
            os.path.join(platform.get_temp_dir(), efs2(u"dfile") +
            str(os.getpid())))

    config = Preferences().initWithDict(config)
    ef = lambda e: errorfunc(logging.WARNING, e)
    platform.write_pid_file(config['pid'], ef)

    t = None
    try:
        r = RawServer(config)
        t = Tracker(config, r)
        try:
            #DEBUG
            print "track: create_serversocket, port=", config['port']
            #END
            s = r.create_serversocket(config['port'], config['bind'], True)
            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-console" )
        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)

        # returned from here config['save_in'] is /home/dave/Desktop/...
        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():
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)
        smart_gettext_and_install('bittorrent', locale_root,
                                  languages=[config['language']])

    if config.has_key('bind') and config['bind'] != '':
        bind_tracker_connection(config['bind'])

    if config.has_key('launch_on_startup'):
        enforce_shortcut(config, log_func=sys.stderr.write)

    if os.name == 'nt' and config.has_key('enforce_association'):
        enforce_association()

    if config.has_key('save_in') and config['save_in'] == '' and \
       (not config.has_key("save_as") or config['save_as'] == '' ) \
       and uiname != 'bittorrent':
        config['save_in'] = decode_from_filesystem(get_save_dir())

    incomplete = decode_from_filesystem(get_incomplete_data_dir())
    if config.get('save_incomplete_in') == '':
        config['save_incomplete_in'] = incomplete
    if config.get('save_incomplete_in') == get_old_incomplete_data_dir():
        config['save_incomplete_in'] = incomplete

    if uiname == "test-client" or (uiname.startswith("bittorrent")
                                   and uiname != 'bittorrent-tracker'):
        if not config.get('ask_for_save'):
            # we check for existance, so things like "D:\" don't trip us up.
            if (config['save_in'] and
                not os.path.exists(config['save_in'])):
                try:
                    os.makedirs(config['save_in'])