Beispiel #1
0
    def main(self):
        """\
        Start the Mainline client and block forever listening for connectons
        """

        uiname = "bittorrent-console"
        defaults = get_defaults(uiname)
        config, args = configfile.parse_configuration_and_args(
            defaults, uiname)
        config = Preferences().initWithDict(config)
        data_dir = config['data_dir']
        self.core_doneflag = DeferredEvent()
        self.rawserver_doneflag = DeferredEvent()

        rawserver = RawServer(config)  #event and I/O scheduler
        self.multitorrent = MultiTorrent(
            config, rawserver,
            data_dir)  #class used to add, control and remove torrents

        self.tick()  #add periodic function call

        rawserver.add_task(0, self.core_doneflag.addCallback,
                           lambda r: rawserver.external_add_task(0, shutdown))
        rawserver.listen_forever(
            self.rawserver_doneflag)  # runs until the component terminates

        self.send(producerFinished(self), "signal")
        print "TorrentClient has shutdown"
Beispiel #2
0
    def run(self):
        try:
            self.multitorrent = Multitorrent(self.config, self.doneflag,
                                             self.global_error)
            # raises BTFailure if bad
            metainfo = ConvertedMetainfo(bdecode(self.metainfo))
            torrent_name = metainfo.name_fs
            if self.config['save_as']:
                if self.config['save_in']:
                    raise BTFailure(
                        _("You cannot specify both --save_as and "
                          "--save_in"))
                saveas = self.config['save_as']
            elif self.config['save_in']:
                saveas = os.path.join(self.config['save_in'], torrent_name)
            else:
                saveas = torrent_name

            self.d.set_torrent_values(metainfo.name, os.path.abspath(saveas),
                                      metainfo.total_bytes,
                                      len(metainfo.hashes))
            self.torrent = self.multitorrent.start_torrent(
                metainfo, Preferences(self.config), self, saveas)
        except BTFailure, e:
            print str(e)
            return
Beispiel #3
0
def create_multitorrent(config, rawserver, i):
    config = Preferences().initWithDict(dict(config))
    config['data_dir'] = config['data_dir'] + ("_%s" % i)
    if os.path.exists(config['data_dir']):
        shutil.rmtree(config['data_dir'])
    for d in ('', 'resume', 'metainfo', 'torrents'):
        ddir = os.path.join(config['data_dir'], d)
        no_really_makedirs(ddir)
    multitorrent = MultiTorrent(config,
                                rawserver,
                                config['data_dir'],
                                init_torrents=False)

    # Butlers
    multitorrent.add_policy(DownloadTorrentButler(multitorrent))
    multitorrent.add_policy(SeedTorrentButler(multitorrent))

    # register shutdown action
    def shutdown():
        df = multitorrent.shutdown()
        stop_rawserver = lambda r: rawserver.stop()
        df.addCallbacks(stop_rawserver, stop_rawserver)

    rawserver.add_task(0, core_doneflag.addCallback,
                       lambda r: rawserver.external_add_task(0, shutdown))
    return multitorrent
Beispiel #4
0
 def start_new_torrent(self, data, save_as=None):
     t = TorrentInfo(Preferences(self.config))
     try:
         t.metainfo = ConvertedMetainfo(bdecode(data))
     except Exception, e:
         self.global_error(
             ERROR,
             _("This is not a valid torrent file. (%s)") % str(e))
         return
Beispiel #5
0
        def run(self,scrwin, config):
            self.displayer = CursesDisplayer(scrwin)

            log_handler = LaunchManyApp.LogHandler(STDERR, self.displayer)
            log_handler.setFormatter(bt_log_fmt)
            logging.getLogger('').addHandler(log_handler)
            logging.getLogger().setLevel(STDERR)
            logging.getLogger('').removeHandler(console)

            # more liberal with logging launchmany-curses specific output.
            lmany_logger = logging.getLogger('launchmany-curses')
            lmany_handler = LaunchManyApp.LogHandler(INFO, self.displayer)
            lmany_handler.setFormatter(bt_log_fmt)
            lmany_logger.setLevel(INFO)
            lmany_logger.addHandler(lmany_handler)

            config = Preferences().initWithDict(config)
            LaunchMany(config, self.displayer.display, 'launchmany-curses')
Beispiel #6
0
    def run(self, scrwin):
        def reread():
            self.multitorrent.rawserver.external_add_task(
                self.reread_config, 0)

        def ulrate(value):
            self.multitorrent.set_option('max_upload_rate', value)
            self.torrent.set_option('max_upload_rate', value)

        self.d = CursesDisplayer(scrwin, self.errlist, self.doneflag, reread,
                                 ulrate)
        try:
            self.multitorrent = Multitorrent(self.config, self.doneflag,
                                             self.global_error)
            # raises BTFailure if bad
            metainfo = ConvertedMetainfo(bdecode(self.metainfo))
            torrent_name = metainfo.name_fs
            if config['save_as']:
                if config['save_in']:
                    raise BTFailure(
                        _("You cannot specify both --save_as and "
                          "--save_in"))
                saveas = config['save_as']
            elif config['save_in']:
                saveas = os.path.join(config['save_in'], torrent_name)
            else:
                saveas = torrent_name

            self.d.set_torrent_values(metainfo.name, os.path.abspath(saveas),
                                      metainfo.total_bytes,
                                      len(metainfo.hashes))
            self.torrent = self.multitorrent.start_torrent(
                metainfo, Preferences(self.config), self, saveas)
        except BTFailure, e:
            errlist.append(str(e))
            return
Beispiel #7
0
 def _restore_state(self):
     def decode_line(line):
         hashtext = line[:40]
         try:
             infohash = hashtext.decode('hex')
         except:
             raise BTFailure(_("Invalid state file contents"))
         if len(infohash) != 20:
             raise BTFailure(_("Invalid state file contents"))
         try:
             path = os.path.join(self.config['data_dir'], 'metainfo',
                                 hashtext)
             f = file(path, 'rb')
             data = f.read()
             f.close()
         except Exception, e:
             try:
                 f.close()
             except:
                 pass
             self.global_error(
                 ERROR, (_("Error reading file \"%s\".") % path) + " (" +
                 str(e) + "), " + _("cannot restore state completely"))
             return None
         if infohash in self.torrents:
             raise BTFailure(_("Invalid state file (duplicate entry)"))
         t = TorrentInfo(Preferences(self.config))
         self.torrents[infohash] = t
         try:
             t.metainfo = ConvertedMetainfo(bdecode(data))
         except Exception, e:
             self.global_error(
                 ERROR,
                 (_("Corrupt data in \"%s\", cannot restore torrent.") %
                  path) + '(' + str(e) + ')')
             return None
Beispiel #8
0
           'bittorrent-tracker', args, 0, 0 )
    except ValueError, e:
        print _("error: ") + str_exc(e)
        print _("run with -? for parameter explanations")
        return
    except BTFailure, e:
        print _("error: ") + str_exc(e)
        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'])
            handler = HTTPHandler(t.get, config['min_time_between_log_flushes'])
            r.start_listening(s, handler)
        except socket.error, e:
Beispiel #9
0
 def __init__(self, metainfo, config, interface):
     self.doneflag = threading.Event()
     self.metainfo = metainfo
     self.config = Preferences().initWithDict(config)
     self.d = interface
Beispiel #10
0
 def __init__(self, metainfo, config, errlist):
     self.doneflag = threading.Event()
     self.metainfo = metainfo
     self.config = Preferences().initWithDict(config)
     self.errlist = errlist
Beispiel #11
0
        config, args = configfile.parse_configuration_and_args(
            defaults, 'bittorrent', sys.argv[1:], 0, None)
        config['upnp'] = False
        config['one_connection_per_ip'] = False
        config['log_tracker_info'] = True
        config['rerequest_interval'] = 5
        config['min_peers'] = NUM_PEERS  # -1 for self but +1 for the http seed
        config['start_trackerless_client'] = False
        config['max_download_rate'] = 180 * 1024
        config['max_upload_rate'] = 30 * 1024
        config['max_files_open'] = 1
    except BTFailure, e:
        print unicode(e.args[0])
        sys.exit(1)

    rawserver = RawServer(Preferences().initWithDict(dict(config)))
    zurllib.set_zurllib_rawserver(rawserver)
    rawserver.install_sigint_handler()

from BitTorrent.MultiTorrent import MultiTorrent
from BTL.ThreadProxy import ThreadProxy
from BitTorrent.TorrentButler import DownloadTorrentButler, SeedTorrentButler
from BTL.formatters import Rate, Size, Duration


class ODict(dict):
    def __getattr__(self, attr):
        return self.get(attr)


def format_status(status):