def download(self, params):
     action = params[0]
     self.logger = logging.getLogger(action)
     
     defaults.extend( [
         ( 'parse_dir_interval', 60,
           "how often to rescan the torrent directory, in seconds" ),
         ( 'recursive_torrents_search', True,
           "search folder for torrents recursively or semi-resursively in launchmany mode" ),
         ( 'saveas_style', 1,
           "How to name torrent downloads (1 = rename to torrent name, " +
           "2 = save under name in torrent, 3 = save in directory under torrent name)" ),
         ( 'display_path', 1,
           "whether to display the full path or the torrent contents for each torrent" ),
     ] )
     try:
         configdir = ConfigDir('launchmany')
         defaultsToIgnore = ['responsefile', 'url', 'priority']
         configdir.setDefaults(defaults,defaultsToIgnore)
         configdefaults = configdir.loadConfig()
         defaults.append(('save_options',0,
          "whether to save the current options as the new default configuration " +
          "(only for btlaunchmany.py)"))
         
         config, args = parseargs(params[1:], defaults, 1, 1, configdefaults)
         if config['save_options']:
             configdir.saveConfig(config)
         configdir.deleteOldCacheData(config['expire_cache_data'])
         if not os.path.isdir(args[0]):
             raise ValueError("Warning: "+args[0]+" is not a directory")
         config['torrent_dir'] = args[0]
     except ValueError, e:
         self.logger.error(str(e) + '\nrun with no args for parameter explanations')
         exit(1)
Example #2
0
    def getBTParams(self, skipcheck = False):
        # Construct BT params
        ###########################
        btparams = []
        
        btparams.append("--display_interval")
        btparams.append(self.config.Read('display_interval'))
        
        # Use single port only
        btparams.append("--minport")
        btparams.append(self.config.Read('minport'))
        btparams.append("--maxport")
        btparams.append(self.config.Read('minport'))
        
#        btparams.append("--random_port")
#        btparams.append(self.config.Read('randomport'))
        
        #if self.config.Read('ipv6') == "1":
        #    btparams.append("--ipv6_enable")
        #    btparams.append(self.config.Read('ipv6'))
        #    btparams.append("--ipv6_binds_v4")
        #    btparams.append(self.config.Read('ipv6_binds_v4'))
        
        # Fast resume
        btparams.append("--selector_enabled")
        btparams.append(self.config.Read('fastresume'))
        
        btparams.append("--auto_kick")
        btparams.append(self.config.Read('kickban'))
        btparams.append("--security")
        btparams.append(self.config.Read('notsameip'))

        btparams.append("--max_upload_rate")
        btparams.append("0")
               
        paramlist = [ "ip", 
                      "bind", 
                      "alloc_rate", 
                      "alloc_type", 
                      "double_check", 
                      "triple_check", 
                      "lock_while_reading", 
                      "lock_files", 
                      "min_peers", 
                      "max_files_open", 
                      "max_connections", 
                      "upnp_nat_access", 
                      "auto_flush" ]
        for param in paramlist:
            value = self.config.Read(param)
            if value != "":
                btparams.append("--" + param)
                btparams.append(value)

        config, args = parseargs(btparams, BTDefaults)
            
        return config
Example #3
0
 def enableTracker(self):
     if self.tracker is None and self.listen_port:
         presets = {'port': self.listen_port,
                    'allowed_dir': os.path.join(utility.configdir.dir_root, 'tracker'),
                    'dfile': os.path.join(utility.getDatabaseDir(), 'tracker.db'),
                   }
         trackconfig, args = parseargs('', defaults, presets = presets)
         self.tracker = Tracker(trackconfig, self.rawserver)
         self.handler.http = HTTPHandler(self.tracker.get, trackconfig['min_time_between_log_flushes'])
Example #4
0
def track(args):
    if len(args) == 0:
        print formatDefinitions(defaults, 80)
        return
    try:
        config, files = parseargs(args, defaults, 0, 0)
    except ValueError, e:
        print 'error: ' + str(e)
        print 'run with no arguments for parameter explanations'
        return
Example #5
0
 def make_torrent(self, filename, dir, trackers):
     source = os.path.join(dir, filename)
     target = os.path.join(dir, filename + '.torrent')
     trackerUris = ['http://{0}:{1}/announce'.format(tracker, defaultSettings['trackerPort']) for tracker in trackers]
     params = [trackerUris[0], source, '--target', target]
     if len(trackerUris) > 1:
         params += ['--announce_list', ','.join(trackerUris[1:])]
     
     config, args = parseargs(params, defaults, 2, None)
     for file in args[1:]:
         make_meta_file(file, args[0], config)
Example #6
0
def make_torrent(filename, dir, trackers):
    source = os.path.join(dir, filename)
    target = os.path.join(dir, filename + '.torrent')
    trackerUris = ['http://{0}:{1}/announce'.format(tracker, defaultSettings['trackerPort']) for tracker in trackers]
    params = [trackerUris[0], source, '--target', target]
    if len(trackerUris) > 1:
        params += ['--announce_list', ','.join(trackerUris[1:])]

    try:
        config, args = parseargs(params, defaults, 2, None)
        for file in args[1:]:
            make_meta_file(file, args[0], config)
    except ValueError, e:
        print 'error: ' + str(e)
        print 'run with no args for parameter explanations'
    def __init__(self,output,args=[],banfunc=None):
        Thread.__init__(self)

        self.output = output
        config,args = parseargs(args,defaults,0,0)
        self.config = config
        self.banfunc = banfunc
        self.policy = policy.get_policy()

        #self.torrent_dir = config['torrent_dir']
        #self.torrent_cache = {}
        #self.file_cache = {}
        #self.blocked_files = {}
        #self.scan_period = config['parse_dir_interval']
        self.stats_period = config['display_interval']

        self.torrent_list = []
        self.downloads = {}
        self.counter = 0
        self.doneflag = Event()

        self.hashcheck_queue = []
        self.hashcheck_current = None

        self.rawserver = RawServer(self.doneflag, config['timeout_check_interval'],
                          config['timeout'], ipv6_enable = config['ipv6_enabled'],
                          failfunc = self.failed, errorfunc = self.exchandler)

        self.upnp = UPnP_test(self.policy(policy.UPNP_NAT_ACCESS))

        while True:
            try:
                if self.policy(policy.USE_SINGLE_PORT):
                    self.listen_port = self.rawserver.find_and_bind(
                                    config['minport'], config['maxport'], config['bind'],
                                    ipv6_socket_style = config['ipv6_binds_v4'],
                                    upnp = self.upnp,
                                    randomizer = self.policy(policy.RANDOM_PORT))
                else:
                    self.listen_port = None
                break
            except socketerror, e:
                if self.upnp and e == UPnP_ERROR:
                    self.output.message('WARNING: COULD NOT FORWARD VIA UPnP')
                    self.upnp = 0
                    continue
                self.failed("Couldn't listen - " + str(e))
                return
Example #8
0
def main(argv):
    program, ext = os.path.splitext(os.path.basename(argv[0]))
    usage = "Usage: %s <trackerurl> <file> [file...] [params...]" % program

    if len(argv) < 3:
        print "{}\n\n{}{}".format(usage, formatDefinitions(defaults, 80),
                                  announcelist_details)
        return 2

    try:
        config, args = parseargs(argv[1:], defaults, 2, None)
        for file in args[1:]:
            make_meta_file(file, args[0], config.copy(), progress=prog)
    except ValueError as e:
        print 'error: ' + str(e)
        print 'run with no args for parameter explanations'

    return 0
    def render_GET(self, request):
        global tracker
        global downloaders
        
        self.log(request.uri)

        verb = request.args['action'][0]
        if verb=='track':
            port = request.args['port'][0]
            params = ['--port', port, '--dfile', 'dstate', '--logfile', defaultDirs['log'] + 'tracker.log']
            d = threads.deferToThread(tracker.track, params)
            # clear the "done" event for the next start
            d.addCallback(lambda x: tracker.init())
            return 'Tracker is listening on {0}.'.format(port)
        elif verb=='seed' or verb=='download':
            torrent = request.args['torrent'][0]
            parts = urlparse(torrent)
            components = os.path.normpath(parts.path).split(os.sep)
            torrentName = components[len(components)-1]
            filename = torrentName[:torrentName.find('.torrent')]
            params = [verb, '--url', torrent, '--saveas', defaultDirs[verb] + filename, '--ip', request.host.host, '--minport', 56969, '--maxport', 56970, '--logfile', '{0}{1}.log'.format(defaultDirs['log'], verb)]
            h = HeadlessDownloader(removeDownloader)
            downloaders[torrent] = h
            d = threads.deferToThread(h.download, params)
            #d.addCallback(h.downloadCallback)
            return '{0} {1}.'.format(verb, torrent)
        elif verb=='maketorrent':
            if tracker.port==0:
                return 'Tracker is not started yet.'

            source = request.args['source'][0]
            filename = defaultDirs['seed'] + source
            target = defaultDirs['torrent'] + source + '.torrent'
            trackerUri = 'http://{0}:{1}/announce'.format(request.host.host, str(tracker.port))
            params = [trackerUri, filename, '--target', target]
            
            try:
                config, args = parseargs(params, defaults, 2, None)
                for file in args[1:]:
                    make_meta_file(file, args[0], config)
            except ValueError, e:
                return 'error: ' + str(e)
            return 'Make torrent for {0}'.format(source)
Example #10
0
def track(args):
    if len(args) == 0:
        print formatDefinitions(defaults, 80)
        return
    try:
        config, files = parseargs(args, defaults, 0, 0)
    except ValueError as e:
        print 'error: ' + str(e)
        print 'run with no arguments for parameter explanations'
        return
    r = RawServer(threading.Event(), config['timeout_check_interval'],
                  config['socket_timeout'], ipv6_enable=config['ipv6_enabled'])
    t = Tracker(config, r)
    r.bind(config['port'], config['bind'],
           reuse=True, ipv6_socket_style=config['ipv6_binds_v4'])
    r.listen_forever(
        HTTPHandler(t.get, config['min_time_between_log_flushes']))
    t.save_state()
    print '# Shutting down: ' + isotime()
Example #11
0
def main(argv):
    program, ext = os.path.splitext(os.path.basename(argv[0]))
    usage = "Usage: %s <trackerurl> <dir> [dir...] [params...]" % program
    desc = "Make a .torrent file for every file or directory present in " \
        "each given directory"

    if len(argv) < 3:
        print "{}\n{}\n{}{}".format(usage, desc,
                                    formatDefinitions(defaults, 80),
                                    announcelist_details)
        return 2

    try:
        config, args = parseargs(argv[1:], defaults, 2, None)
        for dir in args[1:]:
            completedir(dir, args[0], config)
    except ValueError as e:
        print 'error: ' + str(e)
        print 'run with no args for parameter explanations'
        return 1

    return 0
Example #12
0
def main(argv):
    program, ext = os.path.splitext(os.path.basename(argv[0]))
    usage = "Usage: %s <trackerurl> <dir> [dir...] [params...]" % program
    desc = "Make a .torrent file for every file or directory present in " \
        "each given directory"

    if len(argv) < 3:
        print "{}\n{}\n{}{}".format(usage, desc,
                                    formatDefinitions(defaults, 80),
                                    announcelist_details)
        return 2

    try:
        config, args = parseargs(argv[1:], defaults, 2, None)
        for dir in args[1:]:
            completedir(dir, args[0], config)
    except ValueError as e:
        print 'error: ' + str(e)
        print 'run with no args for parameter explanations'
        return 1

    return 0
Example #13
0
    ])
    try:
        configdir = ConfigDir('launchmany')
        defaultsToIgnore = ['responsefile', 'url', 'priority']
        configdir.setDefaults(defaults, defaultsToIgnore)
        configdefaults = configdir.loadConfig()
        defaults.append(
            ('save_options', 0, 'whether to save the current options as the '
             'new default configuration (only for btlaunchmany.py)'))
        if len(sys.argv) < 2:
            print "Usage: btlaunchmany.py <directory> <global options>\n"
            print "<directory> - directory to look for .torrent files " \
                "(semi-recursive)"
            print get_usage(defaults, 80, configdefaults)
            sys.exit(1)
        config, args = parseargs(sys.argv[1:], defaults, 1, 1, configdefaults)
        if config['save_options']:
            configdir.saveConfig(config)
        configdir.deleteOldCacheData(config['expire_cache_data'])
        if not os.path.isdir(args[0]):
            raise ValueError("Warning: " + args[0] + " is not a directory")
        config['torrent_dir'] = args[0]
    except ValueError as e:
        print 'error: {}\nrun with no args for parameter explanations' \
            ''.format(e)
        sys.exit(1)

    LaunchMany(config, HeadlessDisplayer())
    if Exceptions:
        print '\nEXCEPTION:'
        print Exceptions[0]
Example #14
0
    ])
    try:
        configdir = ConfigDir('launchmanycurses')
        defaultsToIgnore = ['responsefile', 'url', 'priority']
        configdir.setDefaults(defaults, defaultsToIgnore)
        configdefaults = configdir.loadConfig()
        defaults.append(('save_options', 0, 'whether to save the current '
                         'options as the new default configuration (only for '
                         'btlaunchmanycurses.py)'))
        if len(sys.argv) < 2:
            print "Usage: btlaunchmanycurses.py <directory> <global options>\n"
            print "<directory> - directory to look for .torrent files " \
                "(semi-recursive)"
            print get_usage(defaults, 80, configdefaults)
            sys.exit(1)
        config, args = parseargs(sys.argv[1:], defaults, 1, 1, configdefaults)
        if config['save_options']:
            configdir.saveConfig(config)
        configdir.deleteOldCacheData(config['expire_cache_data'])
        if not os.path.isdir(args[0]):
            raise ValueError("Warning: " + args[0] + " is not a directory")
        config['torrent_dir'] = args[0]
    except ValueError as e:
        print 'error: {}\nrun with no args for parameter explanations' \
            ''.format(e)
        sys.exit(1)

    curses_wrapper(LaunchManyWrapper, config)
    if Exceptions:
        print '\nEXCEPTION:'
        print Exceptions[0]
        psyco.full()
    except:
        pass

from sys import argv, version, exit
from os.path import split
assert version >= '2', "Install Python 2.0 or greater"
from BitTornado.BT1.makemetafile import make_meta_file, defaults, print_announcelist_details
from BitTornado.parseargs import parseargs, formatDefinitions


def prog(amount):
    print '%.1f%% complete\r' % (amount * 100),

if len(argv) < 3:
    a,b = split(argv[0])
    print 'Usage: ' + b + ' <trackerurl> <file> [file...] [params...]'
    print
    print formatDefinitions(defaults, 80)
    print_announcelist_details()
    print ('')
    exit(2)

try:
    config, args = parseargs(argv[1:], defaults, 2, None)
    for file in args[1:]:
        make_meta_file(file, args[0], config, progress = prog)
except ValueError, e:
    print 'error: ' + str(e)
    print 'run with no args for parameter explanations'
Example #16
0
    try:
        import psyco
        assert psyco.__version__ >= 0x010100f0
        psyco.full()
    except:
        pass

from sys import argv, version, exit
assert version >= '2', "Install Python 2.0 or greater"
from os.path import split
from BitTornado.BT1.makemetafile import defaults, completedir, print_announcelist_details
from BitTornado.parseargs import parseargs, formatDefinitions

if len(argv) < 3:
    a, b = split(argv[0])
    print 'Usage: ' + b + ' <trackerurl> <dir> [dir...] [params...]'
    print 'makes a .torrent file for every file or directory present in each dir.'
    print
    print formatDefinitions(defaults, 80)
    print_announcelist_details()
    print('')
    exit(2)

try:
    config, args = parseargs(argv[1:], defaults, 2, None)
    for dir in args[1:]:
        completedir(dir, args[0], config)
except ValueError, e:
    print 'error: ' + str(e)
    print 'run with no args for parameter explanations'
Example #17
0
    def getBTParams(self, skipcheck = False):
        # Construct BT params
        ###########################
        btparams = []
        
        btparams.append("--display_interval")
        btparams.append(self.config.Read('display_interval'))


        # ipv6
        if sys.version_info >= (2,3) and socket.has_ipv6 and \
           self.config.Read('ipv6', "boolean"):
            btparams.append("--ipv6_enabled")
            btparams.append("1")
            btparams.append("--ipv6_binds_v4")
            btparams.append(self.config.Read('ipv6_binds_v4'))

        # See if we use a fixed port, or pick a random port from a range
        useportrange = self.config.Read('useportrange', 'boolean')
        minport = self.config.Read('minport', "int")
        maxport = self.config.Read('maxport', "int")
        useport = self.config.Read('useport', "int")
        
        # Pick a random port between minport and maxport
        if useportrange or useport < 0:
            useport = str(random.randint(minport, maxport))
        else:
            useport = str(useport)
        self.config.Write('useport', useport)
       
        # Use single port only
        btparams.append("--minport")
        btparams.append(useport)
        btparams.append("--maxport")
        btparams.append(useport)

        # Fast resume
        btparams.append("--selector_enabled")
        btparams.append(self.config.Read('fastresume'))
        
        btparams.append("--auto_kick")
        btparams.append(self.config.Read('kickban'))
        btparams.append("--security")
        btparams.append(self.config.Read('notsameip'))

        btparams.append("--max_upload_rate")
        btparams.append("0")

        # crypto_mode:
        #  @0 disabled
        #  @1 enabled
        #  @2 forced
        #  @3 stealth
        crypto_mode = self.config.Read('crypto_mode', "int")
        btparams.append("--crypto_stealth")
        btparams.append(str(int(crypto_mode==3)))
        btparams.append("--crypto_only")
        btparams.append(str(int(crypto_mode>=2)))
        btparams.append("--crypto_allowed")
        btparams.append(str(int(crypto_mode>=1)))
            
        paramlist = [ "ip", 
                      "bind", 
                      "alloc_rate", 
                      "alloc_type", 
                      "double_check", 
                      "triple_check", 
                      "lock_while_reading", 
                      "lock_files", 
                      "min_peers", 
                      "max_files_open", 
                      "max_connections",
                      "upnp_nat_access",
                      "natpmp",
                      "auto_flush",
                      "pex_allowed",
                      "expire_cache_data"]
        for param in paramlist:
            value = self.config.Read(param)
            if value != "":
                btparams.append("--" + param)
                btparams.append(value)

        config, args = parseargs(btparams, BTDefaults)
        
        config["dht"] = self.config.Read('dht', "boolean")
        config["tracker"] = self.config.Read('tracker', "boolean")
        
        return config