예제 #1
0
    def setup_seeder(self, tdef, seed_dir):
        self.seed_config = SessionStartupConfig()
        self.seed_config.set_torrent_checking(False)
        self.seed_config.set_multicast_local_peer_discovery(False)
        self.seed_config.set_megacache(False)
        self.seed_config.set_dispersy(False)
        self.seed_config.set_mainline_dht(False)
        self.seed_config.set_torrent_store(False)
        self.seed_config.set_enable_torrent_search(False)
        self.seed_config.set_enable_channel_search(False)
        self.seed_config.set_torrent_collecting(False)
        self.seed_config.set_libtorrent(True)
        self.seed_config.set_dht_torrent_collecting(False)
        self.seed_config.set_videoserver_enabled(False)
        self.seed_config.set_enable_metadata(False)
        self.seed_config.set_upgrader_enabled(False)
        self.seed_config.set_tunnel_community_enabled(False)
        self.seed_config.set_state_dir(self.getStateDir(2))

        def start_seed_download(_):
            self.dscfg_seed = DownloadStartupConfig()
            self.dscfg_seed.set_dest_dir(seed_dir)
            d = self.seeder_session.start_download_from_tdef(
                tdef, self.dscfg_seed)
            d.set_state_callback(self.seeder_state_callback)

        self._logger.debug(
            "starting to wait for download to reach seeding state")

        self.seeder_session = Session(self.seed_config, ignore_singleton=True)
        self.seeder_session.start().addCallback(start_seed_download)

        return self.seeding_deferred
예제 #2
0
    def test_create_channel(self):
        """
        Test the pass through function of Session.create_channel to the ChannelManager.
        """

        class LmMock(object):
            class ChannelManager(object):
                invoked_name = None
                invoked_desc = None
                invoked_mode = None

                def create_channel(self, name, description, mode=u"closed"):
                    self.invoked_name = name
                    self.invoked_desc = description
                    self.invoked_mode = mode

            channel_manager = ChannelManager()

        config = SessionStartupConfig()
        session = Session(config, ignore_singleton=True)
        session.lm = LmMock()
        session.lm.api_manager = None

        session.create_channel("name", "description", "open")
        self.assertEqual(session.lm.channel_manager.invoked_name, "name")
        self.assertEqual(session.lm.channel_manager.invoked_desc, "description")
        self.assertEqual(session.lm.channel_manager.invoked_mode, "open")
예제 #3
0
    def initialize(self):
        sscfg = SessionStartupConfig()
        if self._opt.statedir:
            sscfg.set_state_dir(unicode(os.path.realpath(self._opt.statedir)))
        if self._opt.port:
            sscfg.set_dispersy_port(self._opt.port)
        if self._opt.nickname:
            sscfg.set_nickname(self._opt.nickname)

        # pass rss config
        if not self._opt.rss_config:
            self._logger.error(u"rss_config unspecified")
        self.rss_list = parge_rss_config_file(self._opt.rss_config)

        sscfg.set_megacache(True)
        sscfg.set_torrent_collecting(True)
        sscfg.set_torrent_checking(True)
        sscfg.set_enable_torrent_search(True)
        sscfg.set_enable_channel_search(True)

        self._logger.info(u"Starting session...")
        self.session = Session(sscfg)
        self.session.prestart()

        # add dispersy start callbacks
        self.session.add_observer(self.dispersy_started, NTFY_DISPERSY, [NTFY_STARTED])
        self.session.start()
예제 #4
0
def run(params=[""],
        autoload_discovery=True,
        use_torrent_search=True,
        use_channel_search=True):

    from .hacks import patch_crypto_be_discovery
    patch_crypto_be_discovery()

    if len(sys.argv) > 1:
        if sys.platform.startswith("win"):
            from .hacks import get_unicode_sys_argv
            params = get_unicode_sys_argv()[1:]
        else:
            params = sys.argv[1:]
    try:
        # Create single instance semaphore
        single_instance_checker = SingleInstanceChecker("tribler")

        installdir = determine_install_dir()

        if not ALLOW_MULTIPLE and single_instance_checker.IsAnotherRunning():
            statedir = SessionStartupConfig().get_state_dir()

            # Send  torrent info to abc single instance
            if params[0] != "":
                torrentfilename = params[0]
                i2i_port = Utility(installdir,
                                   statedir).read_config('i2ilistenport')
                Instance2InstanceClient(i2i_port, 'START', torrentfilename)

            logger.info("Client shutting down. Detected another instance.")
        else:
            # Launch first abc single instance
            app = wx.GetApp()
            if not app:
                app = TriblerApp(redirect=False)

            abc = ABCApp(params,
                         installdir,
                         autoload_discovery=autoload_discovery,
                         use_torrent_search=use_torrent_search,
                         use_channel_search=use_channel_search)
            app.set_abcapp(abc)
            if abc.frame:
                app.SetTopWindow(abc.frame)
                abc.frame.set_wxapp(app)
                app.MainLoop()

            # since ABCApp is not a wx.App anymore, we need to call OnExit explicitly.
            abc.OnExit()

            # Niels: No code should be present here, only executed after gui closes

        logger.info(
            "Client shutting down. Sleeping for a few seconds to allow other threads to finish"
        )
        sleep(5)

    except:
        print_exc()
    def setup_session_config(self):
        from Tribler.Core.SessionConfig import SessionStartupConfig

        config = SessionStartupConfig()
        config.set_install_dir(
            os.path.abspath(os.path.join(BASE_DIR, "tribler")))
        config.set_state_dir(
            os.path.abspath(
                os.path.join(BASE_DIR, "output", ".Tribler-%d") % getpid()))
        config.set_torrent_checking(False)
        config.set_multicast_local_peer_discovery(False)
        config.set_megacache(False)
        config.set_dispersy(True)
        config.set_mainline_dht(False)
        config.set_torrent_collecting(False)
        config.set_libtorrent(False)
        config.set_dht_torrent_collecting(False)
        config.set_enable_torrent_search(False)
        config.set_enable_channel_search(False)
        config.set_videoserver_enabled(False)
        config.set_http_api_enabled(False)
        config.set_upgrader_enabled(False)
        config.set_listen_port(20000 + self.scenario_runner._peernumber)

        if self.dispersy_port is None:
            self.dispersy_port = 21000 + self.scenario_runner._peernumber
        config.set_dispersy_port(self.dispersy_port)
        logging.error("Dispersy port set to %d" % self.dispersy_port)
        return config
예제 #6
0
    def start_tribler(self):
        config = SessionStartupConfig()
        config.set_state_dir(
            os.path.join(config.get_state_dir(), "tunnel-%d") %
            self.settings.socks_listen_ports[0])
        config.set_torrent_checking(False)
        config.set_multicast_local_peer_discovery(False)
        config.set_megacache(False)
        config.set_dispersy(True)
        config.set_mainline_dht(True)
        config.set_torrent_collecting(False)
        config.set_libtorrent(True)
        config.set_dht_torrent_collecting(False)
        config.set_enable_torrent_search(False)
        config.set_videoserver_enabled(False)
        config.set_dispersy_port(self.dispersy_port)
        config.set_enable_torrent_search(False)
        config.set_enable_channel_search(False)
        config.set_enable_multichain(self.settings.enable_multichain)

        # We do not want to load the TunnelCommunity in the session but instead our own community
        config.set_tunnel_community_enabled(False)

        self.session = Session(config)
        self.session.start()
        logger.info("Using Dispersy port %d" %
                    self.session.get_dispersy_port())
예제 #7
0
    def __init__(self):
        """
        Check whether a lock file exists in the Tribler directory. If not, create the file. If it exists,
        check the PID that is written inside the lock file.
        """
        self.already_running = False

        self.statedir = SessionStartupConfig().get_state_dir()
        self.lock_file_path = os.path.join(self.statedir, LOCK_FILE_NAME)

        if os.path.exists(self.lock_file_path):
            try:
                file_pid = int(self.get_pid_from_lock_file())
            except ValueError:
                # Apparently, the data written inside the lock file is not an int, just remove the file and recreate it.
                self.remove_lock_file()
                self.create_lock_file()
                return

            if file_pid == os.getpid():
                # Ignore when we find our own PID inside the lock file
                self.already_running = False
            elif file_pid != os.getpid() and not ProcessChecker.is_pid_running(
                    file_pid):
                # The process ID written inside the lock file is old, just remove the lock file and create a new one.
                self.remove_lock_file()
                self.create_lock_file()
            else:
                self.already_running = True
        else:
            self.create_lock_file()
예제 #8
0
    def test_create_channel_duplicate_name_error(self):
        self.config = SessionStartupConfig()
        self.session = Session(self.config, ignore_singleton=True)

        class LmMock(object):
            channel_manager = ChannelManager(self.session)

        self.session.lm = LmMock()

        class MockCommunity(object):
            cid = ""

            def get_channel_name(self):
                return "Channel name"

        channel_obj = ChannelObject(self.session,
                                    MockCommunity(),
                                    is_created=True)
        self.session.lm.channel_manager._channel_list = [channel_obj]

        with self.assertRaises(DuplicateChannelNameError) as cm:
            self.session.lm.channel_manager.create_channel(
                "Channel name", "description", "open")
        self.assertEqual(cm.exception.message,
                         u"Channel name already exists: Channel name")
예제 #9
0
파일: compat.py 프로젝트: yorig/tribler
def convertSessionConfig(oldfilename, newfilename):
    # Convert tribler <= 6.2 session config file to tribler 6.3

    # We assume oldfilename exists
    with open(oldfilename, "rb") as f:
        sessconfig = pickle.load(f)

    # Upgrade to new config
    sconfig = SessionStartupConfig()
    for key, value in sessconfig.iteritems():
        if key in ['state_dir', 'install_dir', 'ip', 'minport', 'maxport', 'bind', 'ipv6_enabled',
                   'ipv6_binds_v4', 'timeout', 'timeout_check_interval', 'eckeypairfilename', 'megacache',
                   'nickname', 'mugshot', 'videoanalyserpath', 'peer_icon_path', 'live_aux_seeders']:
            sconfig.sessconfig.set('general', key, value)
        if key in ['mainline_dht', 'mainline_dht_port']:
            sconfig.sessconfig.set('mainline_dht', 'enabled' if key == 'mainline_dht' else key, value)
        if key == 'torrent_checking':
            sconfig.sessconfig.set('torrent_checking', 'enabled', value)
        if key in ['torrent_collecting', 'dht_torrent_collecting', 'torrent_collecting_max_torrents',
                   'torrent_collecting_dir', 'stop_collecting_threshold']:
            sconfig.sessconfig.set('torrent_collecting', 'enabled' if key == 'torrent_collecting' else key, value)
        if key in ['libtorrent', 'lt_proxytype', 'lt_proxyserver', 'lt_proxyauth']:
            sconfig.sessconfig.set('libtorrent', 'enabled' if key == 'libtorrent' else key, value)
        if key in ['dispersy_port', 'dispersy']:
            sconfig.sessconfig.set('dispersy', 'enabled' if key == 'dispersy' else key, value)

    # Save the new file, remove the old one
    sconfig.save(newfilename)
    os.remove(oldfilename)
    return sconfig
예제 #10
0
 def setUp(self):
     yield super(AbstractUpgrader, self).setUp()
     self.config = SessionStartupConfig()
     self.config.set_torrent_collecting_dir(
         os.path.join(self.session_base_dir, 'torrent_collecting_dir'))
     self.session = Session(self.config, ignore_singleton=True)
     self.sqlitedb = None
     self.torrent_store = None
예제 #11
0
    def setUp(self, annotate=True):
        super(TestDHTSession, self).setUp(annotate=annotate)

        config = SessionStartupConfig()
        config.set_state_dir(self.getStateDir())

        self.session = Session(config, ignore_singleton=True)

        self.dht_session = FakeDHTSession(self.session, 'a' * 20, 10)
예제 #12
0
 def get_current_startup_config_copy(self):
     """ Returns a SessionStartupConfig that is a copy of the current runtime
     SessionConfig.
     @return SessionStartupConfig
     """
     # Called by any thread
     with self.sesslock:
         sessconfig = copy.copy(self.sessconfig)
         sessconfig.set_callback(None)
         return SessionStartupConfig(sessconfig=sessconfig)
예제 #13
0
    def convert_session_config(self):
        """
        Convert the sessionconfig.pickle file to libtribler.conf. Do nothing if we do not have a pickle file.
        """
        old_filename = os.path.join(self.session.get_state_dir(),
                                    'sessconfig.pickle')
        new_filename = SessionConfigInterface.get_default_config_filename(
            self.session.get_state_dir())

        if not os.path.exists(old_filename):
            return

        with open(old_filename, "rb") as old_file:
            sessconfig = pickle.load(old_file)

        # Upgrade to new config
        sconfig = SessionStartupConfig()
        for key, value in sessconfig.iteritems():
            if key in [
                    'state_dir', 'install_dir', 'ip', 'minport', 'maxport',
                    'bind', 'ipv6_enabled', 'ipv6_binds_v4', 'timeout',
                    'timeout_check_interval', 'eckeypairfilename', 'megacache',
                    'nickname', 'mugshot', 'videoanalyserpath',
                    'peer_icon_path', 'live_aux_seeders'
            ]:
                sconfig.sessconfig.set('general', key, value)
            if key in ['mainline_dht', 'mainline_dht_port']:
                sconfig.sessconfig.set(
                    'mainline_dht',
                    'enabled' if key == 'mainline_dht' else key, value)
            if key == 'torrent_checking':
                sconfig.sessconfig.set('torrent_checking', 'enabled', value)
            if key in [
                    'torrent_collecting', 'dht_torrent_collecting',
                    'torrent_collecting_max_torrents',
                    'torrent_collecting_dir', 'stop_collecting_threshold'
            ]:
                sconfig.sessconfig.set(
                    'torrent_collecting',
                    'enabled' if key == 'torrent_collecting' else key, value)
            if key in [
                    'libtorrent', 'lt_proxytype', 'lt_proxyserver',
                    'lt_proxyauth'
            ]:
                sconfig.sessconfig.set(
                    'libtorrent', 'enabled' if key == 'libtorrent' else key,
                    value)
            if key in ['dispersy_port', 'dispersy']:
                sconfig.sessconfig.set('dispersy',
                                       'enabled' if key == 'dispersy' else key,
                                       value)

        # Save the new file, remove the old one
        sconfig.save(new_filename)
        os.remove(old_filename)
예제 #14
0
 def setUpPreSession(self):
     self.config = SessionStartupConfig()
     self.config.set_state_dir(self.getStateDir())
     self.config.set_torrent_checking(False)
     self.config.set_multicast_local_peer_discovery(False)
     self.config.set_megacache(False)
     self.config.set_dispersy(False)
     self.config.set_mainline_dht(False)
     self.config.set_torrent_collecting(False)
     self.config.set_libtorrent(False)
     self.config.set_dht_torrent_collecting(False)
     self.config.set_videoserver_enabled(False)
     self.config.set_torrent_store(False)
예제 #15
0
def main(define_communities):
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir",
                                   action="store",
                                   type="string",
                                   help="Use an alternate statedir")
    command_line_parser.add_option("--port",
                                   action="store",
                                   type="int",
                                   help="Listen at this port")
    command_line_parser.add_option("--nickname",
                                   action="store",
                                   type="string",
                                   help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    logger.info(
        "Press Q followed by <ENTER> to stop the channelcast-supporter")

    sscfg = SessionStartupConfig()
    if opt.statedir:
        sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port:
        sscfg.set_listen_port(opt.port)
    if opt.nickname:
        sscfg.set_nickname(opt.nickname)

    sscfg.set_megacache(True)
    sscfg.set_dispersy(True)
    sscfg.set_torrent_collecting(True)

    session = Session(sscfg)
    session.start()

    dispersy = session.get_dispersy_instance()
    define_communities(session)

    try:
        while True:
            x = sys.stdin.readline()
            logger.info(repr(x))
            if x.strip() == 'Q':
                break
    except:
        print_exc()

    session.shutdown()
    logger.info("Shutting down...")
    time.sleep(5)
예제 #16
0
    def start_tribler():
        config = SessionStartupConfig().load()
        config.set_http_api_port(API_PORT)
        config.set_http_api_enabled(True)

        # Check if we are already running a Tribler instance
        process_checker = ProcessChecker()
        if process_checker.already_running:
            return

        session = Session(config)

        signal.signal(signal.SIGTERM, lambda signum, stack: shutdown(session, signum, stack))
        session.start()
예제 #17
0
 def setUpPreSession(self):
     super(TestLibtorrentDownloadImpl, self).setUpPreSession()
     self.config = SessionStartupConfig()
     self.config.set_state_dir(self.getStateDir())
     self.config.set_multicast_local_peer_discovery(False)
     self.config.set_megacache(True)
     self.config.set_dispersy(False)
     self.config.set_tunnel_community_enabled(False)
     self.config.set_mainline_dht(False)
     self.config.set_torrent_collecting(False)
     self.config.set_libtorrent(True)
     self.config.set_dht_torrent_collecting(False)
     self.config.set_videoserver_enabled(False)
     self.config.set_torrent_collecting_dir(os.path.join(self.session_base_dir, 'torrent_collecting_dir'))
예제 #18
0
 def setUp(self):
     super(TestSqliteCacheDB, self).setUp()
     self.config = SessionStartupConfig()
     self.config.set_state_dir(self.getStateDir())
     self.config.set_torrent_checking(False)
     self.config.set_multicast_local_peer_discovery(False)
     self.config.set_megacache(False)
     self.config.set_dispersy(False)
     self.config.set_mainline_dht(False)
     self.config.set_torrent_collecting(False)
     self.config.set_libtorrent(False)
     self.config.set_dht_torrent_collecting(False)
     self.config.set_videoplayer(False)
     self.session = Session(self.config, ignore_singleton=True)
     self.sqlitedb = None
예제 #19
0
    def setUp(self, annotate=True):
        super(TestTorrentChecker, self).setUp(annotate=annotate)

        config = SessionStartupConfig()
        config.set_state_dir(self.getStateDir())
        config.set_megacache(True)

        self.session = Session(config, ignore_singleton=True)
        self.session.start_database()
        self.session.lm.torrent_db = TorrentDBHandler(self.session)
        self.session.lm.torrent_checker = TorrentChecker(self.session)
        self.session.lm.tracker_manager = TrackerManager(self.session)

        self.torrent_checker = self.session.lm.torrent_checker
        self.torrent_checker._torrent_db = self.session.open_dbhandler(NTFY_TORRENTS)
        self.torrent_checker._torrent_db.category = Category()
예제 #20
0
    def __init__(self):

        self.statedir = SessionStartupConfig().get_state_dir()
        self.lock_file_path = os.path.join(self.statedir, LOCK_FILE_NAME)

        if os.path.exists(self.lock_file_path):
            # Check for stale lock file (created before the os was last restarted).
            # The stale file might contain the pid of another running process and
            # not the Tribler itself. To find out we can simply check if the lock file
            # was last modified before os reboot.
            # lock_file_modification_time < system boot time
            file_pid = self.get_pid_from_lock_file()
            if file_pid < 1 or os.path.getmtime(self.lock_file_path) < psutil.boot_time():
                self.remove_lock_file()

        self.already_running = self.is_process_running()
예제 #21
0
 def setUpPreSession(self):
     """ Should set self.config_path and self.config """
     self.config = SessionStartupConfig()
     self.config.set_state_dir(self.getStateDir())
     self.config.set_torrent_checking(False)
     self.config.set_multicast_local_peer_discovery(False)
     self.config.set_megacache(False)
     self.config.set_dispersy(False)
     self.config.set_mainline_dht(False)
     self.config.set_torrent_store(False)
     self.config.set_enable_torrent_search(False)
     self.config.set_enable_channel_search(False)
     self.config.set_torrent_collecting(False)
     self.config.set_libtorrent(False)
     self.config.set_dht_torrent_collecting(False)
     self.config.set_videoplayer(False)
     self.config.set_enable_metadata(False)
     self.config.set_upgrader_enabled(False)
예제 #22
0
 def setUpPreSession(self):
     """ Should set self.config_path and self.config """
     self.config = SessionStartupConfig()
     self.config.set_state_dir(self.getStateDir())
     self.config.set_torrent_checking(False)
     self.config.set_multicast_local_peer_discovery(False)
     self.config.set_megacache(False)
     self.config.set_dispersy(False)
     self.config.set_mainline_dht(False)
     self.config.set_torrent_store(False)
     self.config.set_enable_torrent_search(False)
     self.config.set_enable_channel_search(False)
     self.config.set_torrent_collecting(False)
     self.config.set_libtorrent(False)
     self.config.set_dht_torrent_collecting(False)
     self.config.set_videoserver_enabled(False)
     self.config.set_enable_metadata(False)
     self.config.set_http_api_enabled(False)
     self.config.set_tunnel_community_enabled(False)
     self.config.set_creditmining_enable(False)
     self.config.set_enable_multichain(False)
예제 #23
0
    def test_torrent_store_delete(self):
        config = SessionStartupConfig()
        config.set_torrent_store(True)
        session = Session(config, ignore_singleton=True)
        # Manually set the torrent store as we don't want to start the session.
        session.lm.torrent_store = LevelDbStore(session.get_torrent_store_dir())
        session.lm.torrent_store[hexlify("fakehash")] = "Something"
        self.assertEqual("Something", session.lm.torrent_store[hexlify("fakehash")])
        session.delete_collected_torrent("fakehash")

        raised_key_error = False
        # This structure is needed because if we add a @raises above the test, we cannot close the DB
        # resulting in a dirty reactor.
        try:
            self.assertRaises(KeyError,session.lm.torrent_store[hexlify("fakehash")])
        except KeyError:
            raised_key_error = True
        finally:
            session.lm.torrent_store.close()

        self.assertTrue(raised_key_error)
예제 #24
0
파일: main.py 프로젝트: yorig/tribler
 def start_tribler(self):
     config = SessionStartupConfig()
     config.set_state_dir(
         os.path.join(config.get_state_dir(), "tunnel-%d") %
         self.settings.socks_listen_ports[0])
     config.set_torrent_checking(False)
     config.set_multicast_local_peer_discovery(False)
     config.set_megacache(False)
     config.set_dispersy(True)
     config.set_mainline_dht(True)
     config.set_torrent_collecting(False)
     config.set_libtorrent(True)
     config.set_dht_torrent_collecting(False)
     config.set_enable_torrent_search(False)
     config.set_videoplayer(False)
     config.set_dispersy_port(self.dispersy_port)
     config.set_enable_torrent_search(False)
     config.set_enable_channel_search(False)
     self.session = Session(config)
     upgrader = self.session.prestart()
     while not upgrader.is_done:
         time.sleep(0.1)
     self.session.start()
     logger.info("Using port %d" % self.session.get_dispersy_port())
예제 #25
0
    def setUp(self):
        super(AbstractDB, self).setUp()

        # dummy session
        self.config = SessionStartupConfig()
        self.config.set_state_dir(self.getStateDir())
        self.config.set_torrent_checking(False)
        self.config.set_multicast_local_peer_discovery(False)
        self.config.set_megacache(False)
        self.config.set_dispersy(False)
        self.config.set_mainline_dht(False)
        self.config.set_torrent_collecting(False)
        self.config.set_libtorrent(False)
        self.config.set_dht_torrent_collecting(False)
        self.config.set_videoplayer(False)
        self.config.set_torrent_store(False)
        self.session = Session(self.config, ignore_singleton=True)

        dbpath = init_bak_tribler_sdb('bak_new_tribler.sdb',
                                      destination_path=self.getStateDir(),
                                      overwrite=True)
        self.sqlitedb = SQLiteCacheDB(self.session, busytimeout=BUSYTIMEOUT)
        self.sqlitedb.initialize(dbpath)
        self.session.sqlite_db = self.sqlitedb
예제 #26
0
 def test_startup_session_load_no_filename(self):
     sci = SessionStartupConfig()
     sci.load()
     self.assertTrue(sci)
예제 #27
0
 def test_startup_session_load_corrupt(self):
     sci = SessionStartupConfig()
     sci.load(
         os.path.join(self.CONFIG_FILES_DIR, "corrupt_session_config.conf"))
     self.assertTrue(sci.sessconfig.has_section('general'))
예제 #28
0
    def test_startup_session_save_load(self):
        sci = SessionStartupConfig(CallbackConfigParser())
        file_path = os.path.join(self.session_base_dir, "startupconfig.conf")
        sci.save(file_path)

        sci.load(file_path)
예제 #29
0
    def start_session(self):
        """
        This function loads any previous configuration files from the TRIBLER_STATE_DIR environment variable and then
        starts a Tribler session.
        :return: Nothing.
        """
        if self._running:
            return False

        _logger.info("Set tribler_state_dir to %s" %
                     os.environ['TRIBLER_STATE_DIR'])

        # Load configuration file (if exists)
        cfgfilename = Session.get_default_config_filename(
            os.environ['TRIBLER_STATE_DIR'])
        try:
            self._sconfig = SessionStartupConfig.load(cfgfilename)
            _logger.info("Loaded previous configuration file from %s" %
                         cfgfilename)
        except:
            self._sconfig = SessionStartupConfig()
            self._sconfig.set_state_dir(os.environ['TRIBLER_STATE_DIR'])
            _logger.info(
                "No previous configuration file found, creating one in %s" %
                os.environ['TRIBLER_STATE_DIR'])

        # Set torrent collecting directory:
        dlcfgfilename = get_default_dscfg_filename(
            self._sconfig.get_state_dir())
        _logger.debug("main: Download config %s", dlcfgfilename)
        try:
            defaultDLConfig = DefaultDownloadStartupConfig.load(dlcfgfilename)
        except:
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        if not defaultDLConfig.get_dest_dir():
            defaultDLConfig.set_dest_dir(os.environ['TRIBLER_DOWNLOAD_DIR'])
            self._sconfig.set_torrent_collecting_dir(
                os.path.join(os.environ['TRIBLER_DOWNLOAD_DIR']))

        # Create download directory:
        if not os.path.isdir(defaultDLConfig.get_dest_dir()):
            try:
                _logger.info("Creating download directory: %s" %
                             defaultDLConfig.get_dest_dir())
                os.makedirs(defaultDLConfig.get_dest_dir())
            except:
                _logger.error("Couldn't create download directory! (%s)" %
                              defaultDLConfig.get_dest_dir())

        # TODO: This is temporary for testing:
        from jnius import autoclass
        python_activity = autoclass('org.renpy.android.PythonActivity')
        files_dir = python_activity.mActivity.getFilesDir().getAbsolutePath()
        install_dir = files_dir + u'/lib/python2.7/site-packages'
        _logger.info("Set tribler_install_dir to %s" % install_dir)
        self._sconfig.set_install_dir(install_dir)
        # TODO: ^End of temporary test.

        # Disable unwanted dependencies:
        self._sconfig.set_torrent_store(True)
        self._sconfig.set_torrent_checking(True)
        self._sconfig.set_multicast_local_peer_discovery(False)
        self._sconfig.set_mainline_dht(True)
        self._sconfig.set_dht_torrent_collecting(True)
        self._sconfig.set_torrent_collecting_max_torrents(5000)

        _logger.info("Starting Tribler session..")
        self._session = Session(self._sconfig)
        upgrader = self._session.prestart()
        while not upgrader.is_done:
            time.sleep(0.1)
        self._session.start()
        _logger.info("Tribler session started!")

        self._dispersy = self._session.get_dispersy_instance()
        self.define_communities()
예제 #30
0
 def setUpPreSession(self):
     self.config = SessionStartupConfig()
     self.config.set_state_dir(self.getStateDir())