def main(self):
        print "TorrentClient.run"
        """Main loop"""
        uiname = "bittorrent-console"
        defaults = get_defaults(uiname)
        defaults.append(
            (
                "twisted",
                0,
                _(
                    "Use Twisted network libraries for network connections. 1 means use twisted, 0 means do not use twisted, -1 means autodetect, and prefer twisted"
                ),
            )
        )

        metainfo = None
        config, args = configfile.parse_configuration_and_args(defaults, uiname)

        try:
            metainfo, errors = GetTorrent.get(self.torrentfilename)
            if errors:
                raise BTFailure(_("Error reading .torrent file: ") + "\n".join(errors))
            else:
                self.dl = DLKamaelia(metainfo, config, self)
                self.dl.run()
        except BTFailure, e:
            print str(e)
            sys.exit(1)
Exemple #2
0
        def downloadURL(self, dest_path, url):
            uiname   = 'bittorrent-console'
            defaults = get_defaults(uiname)
            
            # TODO: Bring these in from the plugin's config?
            config_in  = {
                'save_in':                  dest_path,
                'display_interval':         10,
                'max_upload_rate':          8,
                'start_trackerless_client': True,
                'spew':                     False,
                'max_startup_wait':         2 * 60
            }

            try:
                config, args = configfile.parse_configuration_and_args\
                        (defaults, uiname, [], 0, 0)

                config.update(config_in)
                
                metainfo, errors = GetTorrent.get(url)
                if errors:
                    raise BTFailure(_("Error reading .torrent file: ") +\
                        '\n'.join(errors))

            except BTFailure, e:
                self.log.exception("Problem initializing torrent")
                return []
def main(useHelper=False):
	defaults = get_defaults('bittorrent-console')
	config, args = configfile.parse_configuration_and_args(defaults, 'iTorrent',
		sys.argv[1:], 0, 0)
	config = Preferences().initWithDict(config)
	config['tracker_proxy'] = config['http_proxy']
	display = Display()
	btControl = BTControl(config, display)
	os.chdir(config['data_dir'])
	prefix = 'http://localhost'
	if config['control_port'] != 80:
		prefix += ':%d' % config['control_port']
	prefix += '/'

	# TODO: iTunes drops the connection to a torrent download if a concurrent update takes too long. Figure out what the problem is. (Might have been hangups due to DNS queries)
	# TODO: make sure we don't buffer up too much data from socket connections and chew up megabytes of memory.
	# TODO: Allow configuration and feeds.yaml to be re-loaded during runtime.
	Resolver.startResolverThread(btControl.rawServer)
	server = HTTPServer(btControl.rawServer, display, btControl, config, useHelper)
	# TODO: FeedStore should be passed to HTTPServer, not created by it
	utils.tidyDataDir(config['data_dir'], server.feedStore, btControl.rawServer)
	btControl.rawServer.install_sigint_handler()
	if useHelper:
		btControl.rawServer.add_task(MacLauncher.startHelper, 0, (config['control_port'], server.address[1], btControl))
	btControl.rawServer.add_task(display.info, 0, ('Ready on ' + prefix,))
	btControl.start()
Exemple #4
0
def track(args):
    assert type(args) == list and \
           len([x for x in args if type(x)==str])==len(args)

    config = {}
    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: ") + str_exc(e)
        print _("run with -? for parameter explanations")
        return
 def main(self):
     print "TorrentClient.run"
     """Main loop"""
     uiname = 'bittorrent-console'
     defaults = get_defaults(uiname)
     defaults["twisted"] = 0
     metainfo = None
     config, args = configfile.parse_configuration_and_args(defaults, uiname)
     try:
         metainfo, errors = GetTorrent.get( self.torrentfilename )
         if errors:
             raise BTFailure(_("Error reading .torrent file: ") + '\n'.join(errors))
         else:
             self.dl = DLKamaelia(metainfo, config, self)
             self.dl.run()
     except BTFailure, e:
         print str(e)
         sys.exit(1)
Exemple #6
0
    def main(self):
        """\
        Start the Mainline client and block indefinitely, 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")
Exemple #7
0
    def __init__(self,url,save_in,selfish=1):
        self.status = 0
        if __btversion__ >= 4.2:
            uiname = 'bittorrent-console'
        else:
            uiname = 'btdownloadheadless'
        defaults = get_defaults(uiname)

        try:
            config, args = configfile.parse_configuration_and_args(defaults,
                                      uiname)

            config["url"] = url
            config["save_in"] = save_in
            config["selfish"] = selfish


            if args:
                if config['responsefile']:
                    raise BTFailure, 'must have responsefile as arg or ' \
                          'parameter, not both'
                config['responsefile'] = args[0]
            try:
                if config['responsefile']:
                    h = file(config['responsefile'], 'rb')
                    metainfo = h.read()
                    h.close()
                elif config['url']:
                    h = urlopen(config['url'])
                    metainfo = h.read()
                    h.close()
                else:
                    raise BTFailure('you need to specify a .torrent file')
            except IOError, e:
                raise BTFailure('Error reading .torrent file: ', str(e))
        except BTFailure, e:
            print str(e)
            self.status = 1
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Written by Bram Cohen

app_name = "BitTorrent"
from BTL.translation import _

import sys
import locale
from BitTorrent.defaultargs import get_defaults
from BitTorrent import configfile
from BitTorrent.makemetafile import make_meta_files
from BitTorrent.parseargs import parseargs, printHelp
from BitTorrent import BTFailure

defaults = get_defaults('maketorrent-console')
defaults.extend([
    ('target', '',
     _("optional target file for the torrent")),
    ])

defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc

def dc(v):
    print v

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

if __name__ == '__main__':
assert sys.version_info >= (2, 3), "Install Python 2.3 or greater"

from threading import Event

import gtk
import gobject

from BitTorrent.GUI import *
from BitTorrent import Desktop
from BitTorrent import version
from BitTorrent import configfile
from BitTorrent.defaultargs import get_defaults
from BitTorrent.makemetafile import make_meta_files
from BitTorrent.parseargs import makeHelp

defaults = get_defaults('btmaketorrentgui')
defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc


class MainWindow(Window):

    def __init__(self, config):
        Window.__init__(self)
        self.mainwindow = self # temp hack to make modal win32 file choosers work
        self.connect('destroy', self.quit)
        self.set_title('%s metafile creator %s'%(app_name, version))
        self.set_border_width(SPACING)

        self.config = config
from BitTorrent import version
from BitTorrent import configfile
from BitTorrent.GUI_wx import SPACING, BTApp, BTFrameWithSizer, BTDialog, BTPanel, Grid, VSizer, HSizer, ChooseFileOrDirectorySizer
from BitTorrent.UI import Size
from BitTorrent.defaultargs import get_defaults
from BitTorrent.makemetafile import make_meta_files
from BitTorrent.parseargs import makeHelp
from BitTorrent.platform import app_name, btspawn

from BTL.yielddefer import launch_coroutine

import wx
import wx.grid

defaults = get_defaults('maketorrent')
defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc
ui_options = ('torrent_dir','piece_size_pow2','tracker_list','use_tracker')

EXTENSION = '.torrent'

MAXIMUM_NODES = 8


class MakeTorrentPanel(BTPanel):
    sizer_class = VSizer
    sizer_args = ()


Exemple #11
0
def getTorrent(feedName, torrent, maxUploadRate, saveLocation, saveName):
    from BitTorrent.download import Feedback, Multitorrent
    from BitTorrent.defaultargs import get_defaults
    from BitTorrent.parseargs import printHelp
    from BitTorrent.zurllib import urlopen
    from BitTorrent.bencode import bdecode
    from BitTorrent.ConvertedMetainfo import ConvertedMetainfo
    from BitTorrent import configfile
    from BitTorrent import BTFailure
    from BitTorrent import version
    import re, threading

    uiname = "bittorrent-console"
    defaults = get_defaults(uiname)
    config, args = configfile.parse_configuration_and_args(defaults, uiname, "", 0, 1)

    def fmtsize(n):
        return float(n)

    class DL(Feedback):
        def __init__(self, metainfo, config):

            self.doneflag = threading.Event()
            self.metainfo = metainfo
            self.config = config

            logIt("BT url: %s" % self.config["url"])
            logIt("BT save_as: %s" % self.config["save_as"])
            if self.config["max_upload_rate"] > 0:
                logIt("BT max_upload_rate: %s" % str(self.config["max_upload_rate"]))

        def run(self):
            import os

            try:
                config = self.config
                self.d = HeadlessDisplayer(self.doneflag)
                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_namef

                self.d.set_torrent_values(
                    metainfo.name, os.path.abspath(saveas), metainfo.total_bytes, len(metainfo.hashes)
                )
                self.torrent = self.multitorrent.start_torrent(metainfo, self.config, self, saveas)
            except BTFailure, e:
                globals()["torrentStatus"] = 0
                logIt(str(e))
                return
            self.get_status()
            self.multitorrent.rawserver.listen_forever()
            self.d.display({"activity": "shutting down", "fractionDone": 0})
            self.torrent.shutdown()

        def reread_config(self):
            try:
                newvalues = configfile.get_config(self.config, "btdownloadcurses")
            except Exception, e:
                globals()["torrentStatus"] = 0
                self.d.error("Error reading config: " + str(e))
                return
            self.config.update(newvalues)
            # The set_option call can potentially trigger something that kills
            # the torrent (when writing this the only possibility is a change in
            # max_files_open causing an IOError while closing files), and so
            # the self.failed() callback can run during this loop.
            for option, value in newvalues.iteritems():
                self.multitorrent.set_option(option, value)
            for option, value in newvalues.iteritems():
                self.torrent.set_option(option, value)
assert sys.version_info >= (2, 3), "Install Python 2.3 or greater"

from threading import Event

import gtk
import gobject

from BitTorrent.GUI import *
from BitTorrent import Desktop
from BitTorrent import version
from BitTorrent import configfile
from BitTorrent.defaultargs import get_defaults
from BitTorrent.makemetafile import make_meta_files

defaults = get_defaults('btmaketorrentgui')
defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc


class MainWindow(Window):
    def __init__(self, config):
        Window.__init__(self)
        self.connect('destroy', self.quit)
        self.set_title('%s metafile creator %s' % (app_name, version))
        self.set_border_width(SPACING)

        self.config = config

        right_column_width = 276
        self.box = gtk.VBox(spacing=SPACING)
Exemple #13
0
# License.

# Written by Bram Cohen

app_name = "BitTorrent"
from BTL.translation import _

import sys
import locale
from BitTorrent.defaultargs import get_defaults
from BitTorrent import configfile
from BitTorrent.makemetafile import make_meta_files
from BitTorrent.parseargs import parseargs, printHelp
from BitTorrent import BTFailure

defaults = get_defaults('maketorrent-console')
defaults.extend([
    ('target', '',
     _("optional target file for the torrent")),
    ])

defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc

def dc(v):
    print v

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

if __name__ == '__main__':
Exemple #14
0
assert sys.version_info >= (2, 3), _("Install Python %s or greater") % '2.3'

from BitTorrent import BTFailure, inject_main_logfile
from BitTorrent import configfile

from BTL.defer import DeferredEvent, wrap_task
from BitTorrent.defaultargs import get_defaults
from BitTorrent.IPC import ipc_interface
from BitTorrent.prefs import Preferences
from BitTorrent.RawServer_twisted import RawServer
if os.name == 'nt':
    from BitTorrent.platform import win_version_num
from BitTorrent import zurllib

defaults = get_defaults('bittorrent')
defaults.extend((
    ('donated', '', ''),  # the version that the user last donated for
    ('notified', '', ''),  # the version that the user was last notified of
))

defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc

inject_main_logfile()
global_logger = logging.getLogger('')
rawserver = None

if __name__ == '__main__':

    psyco = None
Exemple #15
0
assert sys.version_info >= (2, 3), _("Install Python %s or greater") % '2.3'

from BitTorrent import BTFailure, inject_main_logfile
from BitTorrent import configfile

from BTL.defer import DeferredEvent, wrap_task
from BitTorrent.defaultargs import get_defaults
from BitTorrent.IPC import ipc_interface
from BitTorrent.prefs import Preferences
from BitTorrent.RawServer_twisted import RawServer
if os.name == 'nt':
    from BitTorrent.platform import win_version_num
from BitTorrent import zurllib

defaults = get_defaults('bittorrent')
defaults.extend((('donated' , '', ''), # the version that the user last donated for
                 ('notified', '', ''), # the version that the user was last notified of
                 ))

defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc

inject_main_logfile()
global_logger = logging.getLogger('')
rawserver = None

if __name__ == '__main__':

    psyco = None
    try:
Exemple #16
0
    def global_error(self, level, text):
        self.d.error(text)

    def error(self, torrent, level, text):
        self.d.error(text)

    def failed(self, torrent, is_external):
        self.doneflag.set()

    def finished(self, torrent):
        self.d.finished()


if __name__ == '__main__':
    uiname = 'bittorrent-curses'
    defaults = get_defaults(uiname)

    metainfo = None
    if len(sys.argv) <= 1:
        printHelp(uiname, defaults)
        sys.exit(1)
    try:
        config, args = configfile.parse_configuration_and_args(
            defaults, uiname, sys.argv[1:], 0, 1)

        torrentfile = None
        if len(args):
            torrentfile = args[0]
        for opt in ('responsefile', 'url'):
            if config[opt]:
                print '"--%s"' % opt, _("deprecated, do not use")
                    '"%s": "%s" (%s) - %sP%s%s u%0.1fK/s-d%0.1fK/s u%dK-d%dK "%s"' % (
                    name, status, progress, peers, seeds, seedsmsg,
                    uprate/1000, dnrate/1000, upamt/1024, dnamt/1024, msg))
        return False

def modify_default( defaults_tuplelist, key, newvalue ):
    name,value,doc = [(n,v,d) for (n,v,d) in defaults_tuplelist if n == key][0]
    defaults_tuplelist = [(n,v,d) for (n,v,d) in defaults_tuplelist
                    if not n == key]
    defaults_tuplelist.append( (key,newvalue,doc) )
    return defaults_tuplelist


if __name__ == '__main__':
    uiname = 'launchmany-console'
    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-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/...
Exemple #18
0
from BitTorrent import version
from BitTorrent import configfile
from BitTorrent.GUI_wx import SPACING, BTApp, BTFrameWithSizer, BTDialog, BTPanel, Grid, VSizer, HSizer, ChooseFileOrDirectorySizer
from BitTorrent.UI import Size
from BitTorrent.defaultargs import get_defaults
from BitTorrent.makemetafile import make_meta_files
from BitTorrent.parseargs import makeHelp
from BitTorrent.platform import app_name, btspawn

from BTL.yielddefer import launch_coroutine

import wx
import wx.grid

defaults = get_defaults('maketorrent')
defconfig = dict([(name, value) for (name, value, doc) in defaults])
del name, value, doc
ui_options = ('torrent_dir', 'piece_size_pow2', 'tracker_list', 'use_tracker')

EXTENSION = '.torrent'

MAXIMUM_NODES = 8


class MakeTorrentPanel(BTPanel):
    sizer_class = VSizer
    sizer_args = ()


class MakeTorrentWindow(BTFrameWithSizer):