def setup_tribler_gui_config(self): """ Initialize the TriblerGUI configuration file and make sure that we have all required values. """ configfilepath = os.path.join(self.get_state_dir(), STATEDIR_GUICONFIG) gui_config = CallbackConfigParser() DefaultDownloadStartupConfig.getInstance().set_dest_dir( get_default_dest_dir()) # Load the config file. if os.path.exists(configfilepath): gui_config.read_file(configfilepath, 'utf-8-sig') if not gui_config.has_section('Tribler'): gui_config.add_section('Tribler') for k, v in tribler_defaults['Tribler'].iteritems(): if not gui_config.has_option(k, v): gui_config.set('Tribler', k, v) if not gui_config.has_section('downloadconfig'): gui_config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance( ).dlconfig._sections['downloadconfig'].iteritems(): if not gui_config.has_option(k, v): gui_config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = gui_config gui_config.write_file(configfilepath)
def check_watch_folder(self): if not os.path.isdir(self.session.config.get_watch_folder_path()): return for root, _, files in os.walk(self.session.config.get_watch_folder_path()): for name in files: if not name.endswith(u".torrent"): continue try: tdef = TorrentDef.load_from_memory(fix_torrent(os.path.join(root, name))) except: # torrent appears to be corrupt self.cleanup_torrent_file(root, name) continue infohash = tdef.get_infohash() if not self.session.has_download(infohash): self._logger.info("Starting download from torrent file %s", name) dl_config = DefaultDownloadStartupConfig.getInstance().copy() anon_enabled = self.session.config.get_default_anonymity_enabled() default_num_hops = self.session.config.get_default_number_hops() dl_config.set_hops(default_num_hops if anon_enabled else 0) dl_config.set_safe_seeding(self.session.config.get_default_safeseeding_enabled()) dl_config.set_dest_dir(self.session.config.get_default_destination_dir()) self.session.lm.ltmgr.start_download(tdef=tdef, dconfig=dl_config)
def check_watch_folder(self): if not os.path.isdir(self.session.config.get_watch_folder_path()): return for root, _, files in os.walk( self.session.config.get_watch_folder_path()): for name in files: if not name.endswith(u".torrent"): continue try: tdef = TorrentDef.load_from_memory( fix_torrent(os.path.join(root, name))) except: # torrent appears to be corrupt self.cleanup_torrent_file(root, name) continue infohash = tdef.get_infohash() if not self.session.has_download(infohash): self._logger.info("Starting download from torrent file %s", name) dl_config = DefaultDownloadStartupConfig.getInstance( ).copy() anon_enabled = self.session.config.get_default_anonymity_enabled( ) default_num_hops = self.session.config.get_default_number_hops( ) dl_config.set_hops(default_num_hops if anon_enabled else 0) dl_config.set_safe_seeding( self.session.config.get_default_safeseeding_enabled()) self.session.lm.ltmgr.start_download(tdef=tdef, dconfig=dl_config)
def guiservthread_free_space_check(self): free_space = get_free_space( DefaultDownloadStartupConfig.getInstance().get_dest_dir()) self.frame.SRstatusbar.RefreshFreeSpace(free_space) storage_locations = defaultdict(list) for download in self.utility.session.get_downloads(): if download.get_status() == DLSTATUS_DOWNLOADING: storage_locations[download.get_dest_dir()].append(download) show_message = False low_on_space = [ path for path in storage_locations.keys() if 0 < get_free_space( path) < self.utility.read_config('free_space_threshold') ] for path in low_on_space: for download in storage_locations[path]: download.stop() show_message = True if show_message: wx.CallAfter( wx.MessageBox, "Tribler has detected low disk space. Related downloads have been stopped.", "Error")
def start_download(self, torrentfilename=None, infohash=None, tdef=None, dconfig=None): self._logger.debug(u"starting download: filename: %s, torrent def: %s", torrentfilename, tdef) if infohash is not None: assert isinstance(infohash, str), "infohash type: %s" % type(infohash) assert len(infohash) == 20, "infohash length is not 20: %s, %s" % ( len(infohash), infohash) # the priority of the parameters is: (1) tdef, (2) infohash, (3) torrent_file. # so if we have tdef, infohash and torrent_file will be ignored, and so on. if tdef is None: if infohash is not None: # try to get the torrent from torrent_store if the infohash is provided torrent_data = self.trsession.get_collected_torrent(infohash) if torrent_data is not None: # use this torrent data for downloading tdef = TorrentDef.load_from_memory(torrent_data) if tdef is None: assert torrentfilename is not None, "torrent file must be provided if tdef and infohash are not given" # try to get the torrent from the given torrent file torrent_data = fix_torrent(torrentfilename) if torrent_data is None: raise TorrentFileException( "error while decoding torrent file") tdef = TorrentDef.load_from_memory(torrent_data) assert tdef is not None, "tdef MUST not be None after loading torrent" d = self.trsession.get_download(tdef.get_infohash()) if d: new_trackers = list( set(tdef.get_trackers_as_single_tuple()) - set(d.get_def().get_trackers_as_single_tuple())) if not new_trackers: raise DuplicateDownloadException( "This download already exists.") else: self.trsession.update_trackers(tdef.get_infohash(), new_trackers) return default_dl_config = DefaultDownloadStartupConfig.getInstance() dscfg = default_dl_config.copy() if dconfig is not None: dscfg = dconfig self._logger.info('start_download: Starting in VOD mode') result = self.trsession.start_download_from_tdef(tdef, dscfg) return result
def __init__(self, session, policy=SeederRatioPolicy, load_config=True): self.session = session # Configurable parameter (changeable in runtime -plus sources-) self.max_torrents_active = 20 self.max_torrents_per_source = 10 self.source_interval = 100 self.swarm_interval = 100 # Can't be changed on runtime self.tracker_interval = 200 self.logging_interval = 60 self.share_mode_target = 3 self.policy = policy(session) # Non-Configurable self.initial_logging_interval = 20 self.initial_tracker_interval = 25 self.initial_swarm_interval = 30 self.min_connection_start = 5 self.min_channels_start = 100 self.credit_mining_path = os.path.join( DefaultDownloadStartupConfig.getInstance().get_dest_dir(), CREDIT_MINING_FOLDER_DOWNLOAD) self.load_config = load_config # whether we want to check dependencies of BoostingManager self.check_dependencies = True self.auto_start_source = True
def convert_default_download_config(self): """ Convert the dlconfig.pickle file to a .state file. """ state_dir = self.session.get_state_dir() old_filename = os.path.join(state_dir, 'dlconfig.pickle') new_filename = get_default_dscfg_filename(state_dir) if not os.path.exists(old_filename): return with open(old_filename, "rb") as old_file: dlconfig = pickle.load(old_file) # Upgrade to new config ddsconfig = DefaultDownloadStartupConfig.getInstance() for key, value in dlconfig.iteritems(): if key in [ 'saveas', 'max_upload_rate', 'max_download_rate', 'super_seeder', 'mode', 'selected_files', 'correctedfilename' ]: ddsconfig.dlconfig.set('downloadconfig', key, value) # Save the new file, remove the old one ddsconfig.save(new_filename) os.remove(old_filename) return ddsconfig
def resume_download(self, filename, setupDelay=0): tdef = dscfg = pstate = None try: pstate = self.load_download_pstate(filename) # SWIFTPROC metainfo = pstate.get('state', 'metainfo') if 'infohash' in metainfo: tdef = TorrentDefNoMetainfo(metainfo['infohash'], metainfo['name'], metainfo.get('url', None)) else: tdef = TorrentDef.load_from_dict(metainfo) if pstate.has_option('download_defaults', 'saveas') and \ isinstance(pstate.get('download_defaults', 'saveas'), tuple): pstate.set('download_defaults', 'saveas', pstate.get('download_defaults', 'saveas')[-1]) dscfg = DownloadStartupConfig(pstate) except: # pstate is invalid or non-existing _, file = os.path.split(filename) infohash = binascii.unhexlify(file[:-6]) torrent_data = self.torrent_store.get(infohash) if torrent_data: try: tdef = TorrentDef.load_from_memory(torrent_data) defaultDLConfig = DefaultDownloadStartupConfig.getInstance() dscfg = defaultDLConfig.copy() if self.mypref_db is not None: dest_dir = self.mypref_db.getMyPrefStatsInfohash(infohash) if dest_dir and os.path.isdir(dest_dir): dscfg.set_dest_dir(dest_dir) except ValueError: self._logger.warning("tlm: torrent data invalid") if pstate is not None: has_resume_data = pstate.get('state', 'engineresumedata') is not None self._logger.debug("tlm: load_checkpoint: resumedata %s", 'len %s ' % len(pstate.get('state', 'engineresumedata')) if has_resume_data else 'None') if tdef and dscfg: if dscfg.get_dest_dir() != '': # removed torrent ignoring try: if self.download_exists(tdef.get_infohash()): self._logger.info("tlm: not resuming checkpoint because download has already been added") elif dscfg.get_credit_mining() and not self.session.config.get_credit_mining_enabled(): self._logger.info("tlm: not resuming checkpoint since token mining is disabled") else: self.add(tdef, dscfg, pstate, setupDelay=setupDelay) except Exception as e: self._logger.exception("tlm: load check_point: exception while adding download %s", tdef) else: self._logger.info("tlm: removing checkpoint %s destdir is %s", filename, dscfg.get_dest_dir()) os.remove(filename) else: self._logger.info("tlm: could not resume checkpoint %s %s %s", filename, tdef, dscfg)
def resume_download(self, filename, setupDelay=0): tdef = dscfg = pstate = None try: pstate = self.load_download_pstate(filename) # SWIFTPROC metainfo = pstate.get('state', 'metainfo') if 'infohash' in metainfo: tdef = TorrentDefNoMetainfo(metainfo['infohash'], metainfo['name'], metainfo.get('url', None)) else: tdef = TorrentDef.load_from_dict(metainfo) if pstate.has_option('download_defaults', 'saveas') and \ isinstance(pstate.get('download_defaults', 'saveas'), tuple): pstate.set('download_defaults', 'saveas', pstate.get('download_defaults', 'saveas')[-1]) dscfg = DownloadStartupConfig(pstate) except: # pstate is invalid or non-existing _, file = os.path.split(filename) infohash = binascii.unhexlify(file[:-6]) torrent_data = self.torrent_store.get(infohash) if torrent_data: try: tdef = TorrentDef.load_from_memory(torrent_data) defaultDLConfig = DefaultDownloadStartupConfig.getInstance() dscfg = defaultDLConfig.copy() if self.mypref_db is not None: dest_dir = self.mypref_db.getMyPrefStatsInfohash(infohash) if dest_dir and os.path.isdir(dest_dir): dscfg.set_dest_dir(dest_dir) except ValueError: self._logger.warning("tlm: torrent data invalid") if pstate is not None: has_resume_data = pstate.get('state', 'engineresumedata') is not None self._logger.debug("tlm: load_checkpoint: resumedata %s", 'len %s ' % len(pstate.get('state', 'engineresumedata')) if has_resume_data else 'None') if tdef and dscfg: if dscfg.get_dest_dir() != '': # removed torrent ignoring try: if not self.download_exists(tdef.get_infohash()): self.add(tdef, dscfg, pstate, setupDelay=setupDelay) else: self._logger.info("tlm: not resuming checkpoint because download has already been added") except Exception as e: self._logger.exception("tlm: load check_point: exception while adding download %s", tdef) else: self._logger.info("tlm: removing checkpoint %s destdir is %s", filename, dscfg.get_dest_dir()) os.remove(filename) else: self._logger.info("tlm: could not resume checkpoint %s %s %s", filename, tdef, dscfg)
def test_default_download_startup_config_load(self): with open(os.path.join(self.session_base_dir, "dlconfig.conf"), 'wb') as conf_file: conf_file.write("[Tribler]\nabc=def") ddsc = DefaultDownloadStartupConfig.load( os.path.join(self.session_base_dir, "dlconfig.conf")) self.assertEqual(ddsc.dlconfig.get('Tribler', 'abc'), 'def')
def test_add_duplicate_download(self): """ Testing whether a DuplicateDownloadException is raised when a download is added twice """ self.lm.downloads = {"abcd": None} tdef = TorrentDef() tdef.metainfo_valid = True tdef.infohash = "abcd" self.lm.add(tdef, DefaultDownloadStartupConfig.getInstance())
def __init__(self, config=None): self.max_torrents_active = 8 self.max_torrents_listed = 100 # Note: be sure to set this interval to something that gives torrents a fair chance of # discovering peers and uploading data self.auto_manage_interval = 600 self.hops = 1 # Maximum number of bytes of disk space that credit mining is allowed to use. self.max_disk_space = config.get_credit_mining_disk_space() if config else 50 * 1024 ** 3 self.low_disk_space = 1000 * 1024 ** 2 self.save_path = os.path.join(DefaultDownloadStartupConfig.getInstance().get_dest_dir(), 'credit_mining')
def setupConfig(self): self.configfilepath = os.path.join(self.getConfigPath(), STATEDIR_GUICONFIG) self.config = CallbackConfigParser() # Load the config file. if os.path.exists(self.configfilepath): self.config.read_file(self.configfilepath, 'utf-8-sig') if not self.config.has_section('Tribler'): self.config.add_section('Tribler') # Tribler.conf also contains the default download config. So we need to merge it now. if not self.config.has_section('downloadconfig'): self.config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance( ).dlconfig._sections['downloadconfig'].iteritems(): self.config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = self.config
def start_download(self, torrentfilename=None, infohash=None, tdef=None, dconfig=None): self._logger.debug(u"starting download: filename: %s, torrent def: %s", torrentfilename, tdef) if infohash is not None: assert isinstance(infohash, str), "infohash type: %s" % type(infohash) assert len(infohash) == 20, "infohash length is not 20: %s, %s" % (len(infohash), infohash) # the priority of the parameters is: (1) tdef, (2) infohash, (3) torrent_file. # so if we have tdef, infohash and torrent_file will be ignored, and so on. if tdef is None: if infohash is not None: # try to get the torrent from torrent_store if the infohash is provided torrent_data = self.tribler_session.get_collected_torrent(infohash) if torrent_data is not None: # use this torrent data for downloading tdef = TorrentDef.load_from_memory(torrent_data) if tdef is None: assert torrentfilename is not None, "torrent file must be provided if tdef and infohash are not given" # try to get the torrent from the given torrent file torrent_data = fix_torrent(torrentfilename) if torrent_data is None: raise TorrentFileException("error while decoding torrent file") tdef = TorrentDef.load_from_memory(torrent_data) assert tdef is not None, "tdef MUST not be None after loading torrent" d = self.tribler_session.get_download(tdef.get_infohash()) if d: # If there is an existing credit mining download with the same infohash, remove it and restart if d.get_credit_mining(): self.tribler_session.lm.credit_mining_manager.torrents.pop(hexlify(tdef.get_infohash()), None) self.tribler_session.remove_download(d).addCallback( lambda _, tf=torrentfilename, ih=infohash, td=tdef, dc=dconfig: self.start_download(tf, ih, td, dc) ) return new_trackers = list(set(tdef.get_trackers_as_single_tuple()) - set( d.get_def().get_trackers_as_single_tuple())) if new_trackers: self.tribler_session.update_trackers(tdef.get_infohash(), new_trackers) default_dl_config = DefaultDownloadStartupConfig.getInstance() dscfg = default_dl_config.copy() if dconfig is not None: dscfg = dconfig self._logger.info('start_download: Starting in VOD mode') result = self.tribler_session.start_download_from_tdef(tdef, dscfg) return result
def start_download(self, torrentfilename=None, infohash=None, tdef=None, dconfig=None): self._logger.debug(u"starting download: filename: %s, torrent def: %s", torrentfilename, tdef) if infohash is not None: assert isinstance(infohash, str), "infohash type: %s" % type(infohash) assert len(infohash) == 20, "infohash length is not 20: %s, %s" % (len(infohash), infohash) # the priority of the parameters is: (1) tdef, (2) infohash, (3) torrent_file. # so if we have tdef, infohash and torrent_file will be ignored, and so on. if tdef is None: if infohash is not None: # try to get the torrent from torrent_store if the infohash is provided torrent_data = self.tribler_session.get_collected_torrent(infohash) if torrent_data is not None: # use this torrent data for downloading tdef = TorrentDef.load_from_memory(torrent_data) if tdef is None: assert torrentfilename is not None, "torrent file must be provided if tdef and infohash are not given" # try to get the torrent from the given torrent file torrent_data = fix_torrent(torrentfilename) if torrent_data is None: raise TorrentFileException("error while decoding torrent file") tdef = TorrentDef.load_from_memory(torrent_data) assert tdef is not None, "tdef MUST not be None after loading torrent" default_dl_config = DefaultDownloadStartupConfig.getInstance() dscfg = default_dl_config.copy() if dconfig is not None: dscfg = dconfig d = self.tribler_session.get_download(tdef.get_infohash()) if d: # If there is an existing credit mining download with the same infohash # then move to the user download directory and checkpoint the download immediately. if d.get_credit_mining(): self.tribler_session.lm.credit_mining_manager.torrents.pop(hexlify(tdef.get_infohash()), None) d.set_credit_mining(False) d.move_storage(dscfg.get_dest_dir()) d.checkpoint() new_trackers = list(set(tdef.get_trackers_as_single_tuple()) - set( d.get_def().get_trackers_as_single_tuple())) if new_trackers: self.tribler_session.update_trackers(tdef.get_infohash(), new_trackers) self._logger.info('start_download: Starting in VOD mode') result = self.tribler_session.start_download_from_tdef(tdef, dscfg) return result
def test_add_download_while_credit_mining(self): infohash_str = '00' * 20 infohash_bin = '\00' * 20 magnet = 'magnet:?xt=urn:btih:' + infohash_str def fake_move_storage(dl, dest_dir): dl.dest_dir = dest_dir dl.move_storage_called = True def fake_checkpoint(dl): dl.checkpoint_called = True def set_credit_mining(dl, value): dl.credit_mining = value # Default download directory default_dl_config = DefaultDownloadStartupConfig.getInstance() download_dir = default_dl_config.get_dest_dir() torrent = FakeTorrent(infohash_bin, self.name) torrent.download.move_storage_called = False torrent.download.checkpoint_called = False torrent.download.set_credit_mining = lambda value, dl=torrent.download: set_credit_mining( dl, value) torrent.download.move_storage = lambda dest_dir, dl=torrent.download: fake_move_storage( dl, dest_dir) torrent.download.checkpoint = lambda dl=torrent.download: fake_checkpoint( dl) self.credit_mining_manager.torrents[infohash_str] = torrent # Credit mining downloads should get moved to download directory and be checkpointed self.session.get_download = lambda _: torrent.download self.session.start_download_from_uri(magnet) self.assertNotIn(infohash_str, self.credit_mining_manager.torrents) self.assertTrue(torrent.download.checkpoint_called) self.assertTrue(torrent.download.move_storage_called) self.assertEqual(torrent.download.dest_dir, download_dir) # Non credit mining downloads should not get removed torrent.download.move_storage_called = False torrent.download.checkpoint_called = False torrent.download.get_credit_mining = lambda: False self.session.get_download = lambda _: torrent.download self.assertFalse(torrent.download.move_storage_called) self.assertFalse(torrent.download.checkpoint_called)
def OnBrowse(self, event): dlg = wx.FileDialog(None, "Please select the .torrent file(s).", wildcard="torrent (*.torrent)|*.torrent", style=wx.FD_OPEN | wx.FD_MULTIPLE) path = DefaultDownloadStartupConfig.getInstance().get_dest_dir( ) + os.sep dlg.SetPath(path) if dlg.ShowModal() == wx.ID_OK: filenames = dlg.GetPaths() dlg.Destroy() if self.__processPaths(filenames): self.EndModal(wx.ID_OK) else: dlg.Destroy()
def doAction(self, args): action = args['action'] if action == 'add-url': url = args['s'] destdir = DefaultDownloadStartupConfig.getInstance().get_dest_dir() if url.startswith("http"): self.guiUtility.frame.startDownloadFromUrl(url, destdir) elif url.startswith("magnet:"): self.guiUtility.frame.startDownloadFromMagnet(url, destdir) elif action == 'getprops': return self.doProps(args) elif action == 'getfiles': return self.doFiles(args) elif action == 'getsettings': return self.doSettings(args) elif 'hash' in args: if isinstance(args.get('hash', ''), basestring): infohashes = [args.get('hash', '')] else: infohashes = args['hash'] for h in infohashes: infohash = unhexlify(h) torrent = self.library_manager.getTorrentFromInfohash(infohash) if action in ['start', 'forcestart', 'unpause']: self.library_manager.resumeTorrent(torrent) elif action in ['stop', 'pause']: self.library_manager.stopTorrent(torrent.infohash) elif action == 'remove': self.library_manager.deleteTorrent(torrent) elif action == 'removedata': self.library_manager.deleteTorrent(torrent, removecontent=True) return {}
def OnBrowseDir(self, event): dlg = wx.DirDialog( None, "Please select a directory contain the .torrent files", style=wx.wx.DD_DIR_MUST_EXIST) path = DefaultDownloadStartupConfig.getInstance().get_dest_dir( ) + os.sep dlg.SetPath(path) if dlg.ShowModal() == wx.ID_OK and os.path.isdir(dlg.GetPath()): filenames = [ os.path.join(dlg.GetPath(), file) for file in os.listdir(dlg.GetPath()) ] dlg.Destroy() if self.__processPaths(filenames): self.EndModal(wx.ID_OK) dlg.Destroy()
def lineReceived(self, line): anon_tunnel = self.anon_tunnel if line == 'threads': for thread in threading.enumerate(): logger.debug("%s \t %d", thread.name, thread.ident) elif line == 'c': logger.debug( "========\nCircuits\n========\nid\taddress\t\t\t\t\tgoal\thops\tIN (MB)\tOUT (MB)\tinfohash\ttype" ) for circuit_id, circuit in anon_tunnel.community.circuits.items(): info_hash = circuit.info_hash.encode( 'hex')[:10] if circuit.info_hash else '?' logger.debug( "%d\t%s:%d\t%d\t%d\t\t%.2f\t\t%.2f\t\t%s\t%s" % circuit_id, circuit.first_hop[0], circuit.first_hop[1], circuit.goal_hops, len(circuit.hops), circuit.bytes_down / 1024.0 / 1024.0, circuit.bytes_up / 1024.0 / 1024.0, info_hash, circuit.ctype) elif line.startswith('s'): cur_path = os.getcwd() line_split = line.split(' ') filename = 'test_file' if len(line_split) == 1 else line_split[1] if not os.path.exists(filename): logger.info("Creating torrent..") with open(filename, 'wb') as fp: fp.write(os.urandom(50 * 1024 * 1024)) tdef = TorrentDef() tdef.add_content(os.path.join(cur_path, filename)) tdef.set_tracker("udp://localhost/announce") tdef.set_private() tdef.finalize() tdef.save(os.path.join(cur_path, filename + '.torrent')) else: logger.info("Loading existing torrent..") tdef = TorrentDef.load(filename + '.torrent') logger.info("loading torrent done, infohash of torrent: %s" % (tdef.get_infohash().encode('hex')[:10])) defaultDLConfig = DefaultDownloadStartupConfig.getInstance() dscfg = defaultDLConfig.copy() dscfg.set_hops(1) dscfg.set_dest_dir(cur_path) reactor.callFromThread( anon_tunnel.session.start_download_from_tdef, tdef, dscfg) elif line.startswith('i'): # Introduce dispersy port from other main peer to this peer line_split = line.split(' ') to_introduce_ip = line_split[1] to_introduce_port = int(line_split[2]) self.anon_tunnel.community.add_discovered_candidate( Candidate((to_introduce_ip, to_introduce_port), tunnel=False)) elif line.startswith('d'): line_split = line.split(' ') filename = 'test_file' if len(line_split) == 1 else line_split[1] logger.info("Loading torrent..") tdef = TorrentDef.load(filename + '.torrent') logger.info("Loading torrent done") defaultDLConfig = DefaultDownloadStartupConfig.getInstance() dscfg = defaultDLConfig.copy() dscfg.set_hops(1) dscfg.set_dest_dir( os.path.join( os.getcwd(), 'downloader%s' % anon_tunnel.session.get_dispersy_port())) def start_download(): def cb(ds): logger.info( 'Download infohash=%s, down=%s, progress=%s, status=%s, seedpeers=%s, candidates=%d' % (tdef.get_infohash().encode('hex')[:10], ds.get_current_speed('down'), ds.get_progress(), dlstatus_strings[ds.get_status()], sum(ds.get_num_seeds_peers()), sum(1 for _ in anon_tunnel.community. dispersy_yield_verified_candidates()))) return 1.0, False download = anon_tunnel.session.start_download_from_tdef( tdef, dscfg) download.set_state_callback(cb) reactor.callFromThread(start_download) elif line == 'q': anon_tunnel.should_run = False elif line == 'r': logger.debug("circuit\t\t\tdirection\tcircuit\t\t\tTraffic (MB)") from_to = anon_tunnel.community.relay_from_to for key in from_to.keys(): relay = from_to[key] logger.info("%s-->\t%s\t\t%.2f" % ( (key[0], key[1]), (relay.sock_addr, relay.circuit_id), relay.bytes[1] / 1024.0 / 1024.0, ))
def __init__(self): super(SettingsDialog, self).__init__(None, size=(600, 700), title="Settings", name="settingsDialog", style=wx.DEFAULT_DIALOG_STYLE) self.SetExtraStyle(self.GetExtraStyle() | wx.WS_EX_VALIDATE_RECURSIVELY) self._logger = logging.getLogger(self.__class__.__name__) self.guiUtility = GUIUtility.getInstance() self.utility = self.guiUtility.utility self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance() # create the dialog and widgets self._tree_ctrl = wx.TreeCtrl(self, style=wx.TR_DEFAULT_STYLE | wx.SUNKEN_BORDER | wx.TR_HIDE_ROOT | wx.TR_SINGLE) self._tree_ctrl.SetMinSize(wx.Size(150, -1)) tree_root = self._tree_ctrl.AddRoot('Root') self._tree_ctrl.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnSelectionChanging) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self._tree_ctrl, 0, wx.EXPAND | wx.RIGHT, 10) self._general_panel, self._general_id = self.__create_s1( tree_root, hsizer) self._conn_panel, self._conn_id = self.__create_s2(tree_root, hsizer) self._bandwidth_panel, self._bandwidth_id = self.__create_s3( tree_root, hsizer) self._seeding_panel, self._seeding_id = self.__create_s4( tree_root, hsizer) self._experimental_panel, self._experimental_id = self.__create_s5( tree_root, hsizer) self._tunnel_panel, self._tunnel_id = self.__create_s6( tree_root, hsizer) self._general_panel.Show(True) self._conn_panel.Show(False) self._bandwidth_panel.Show(False) self._seeding_panel.Show(False) self._experimental_panel.Show(False) self._tunnel_panel.Show(False) self._save_btn = wx.Button(self, wx.ID_OK, label="Save") self._cancel_btn = wx.Button(self, wx.ID_CANCEL, label="Cancel") btn_sizer = wx.StdDialogButtonSizer() btn_sizer.AddButton(self._save_btn) btn_sizer.AddButton(self._cancel_btn) btn_sizer.Realize() self._save_btn.Bind(wx.EVT_BUTTON, self.saveAll) self._cancel_btn.Bind(wx.EVT_BUTTON, self.cancelAll) vsizer = wx.BoxSizer(wx.VERTICAL) vsizer.Add(hsizer, 1, wx.EXPAND | wx.ALL, 10) vsizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 5) self.SetSizer(vsizer) # select General page by default self._tree_ctrl.SelectItem(self._general_id)
def test_default_download_startup_config_init(self): _ = DefaultDownloadStartupConfig.getInstance() DefaultDownloadStartupConfig()
def tearDown(self, annotate=True): # TODO(ardhi) : remove it when Tribler free of singleton # and 1 below DefaultDownloadStartupConfig.delInstance() super(TestBoostingManagerUtilities, self).tearDown()
def tearDown(self, annotate=True): DefaultDownloadStartupConfig.delInstance() self.session.lm.boosting_manager.cancel_all_pending_tasks() super(TestBoostingManagerError, self).tearDown()
def test_default_download_startup_config_load(self): with open(os.path.join(self.session_base_dir, "dlconfig.conf"), 'wb') as conf_file: conf_file.write(b"[Tribler]\nabc=def") ddsc = DefaultDownloadStartupConfig.load(os.path.join(self.session_base_dir, "dlconfig.conf")) self.assertEqual(ddsc.dlconfig.get('Tribler', 'abc'), 'def')
def tearDown(self): super(TestConfigParser, self).tearDown() # Make sure we don't leave a DefaultDownloadStartupConfig instance behind DefaultDownloadStartupConfig.delInstance()
def tearDown(self, annotate=True): DefaultDownloadStartupConfig.delInstance() self.boosting_manager.shutdown() yield super(TestBoostingManagerSys, self).tearDown(annotate=annotate)
def __init__(self, params, installdir, autoload_discovery=True, use_torrent_search=True, use_channel_search=True): super(ABCApp, self).__init__() assert not isInIOThread( ), "isInIOThread() seems to not be working correctly" self._logger = logging.getLogger(self.__class__.__name__) self.params = params self.installdir = installdir self.state_dir = None self.error = None self.last_update = 0 self.ready = False self.done = False self.frame = None self.upgrader = None self.i2i_server = None # DISPERSY will be set when available self.dispersy = None self.tunnel_community = None self.webUI = None self.utility = None # Stage 1 start session = self.InitStage1(installdir, autoload_discovery=autoload_discovery, use_torrent_search=use_torrent_search, use_channel_search=use_channel_search) try: self._logger.info('Client Starting Up.') self._logger.info("Tribler is using %s as working directory", self.installdir) # Stage 2: show the splash window and start the session self.utility = Utility(self.installdir, session.get_state_dir()) if self.utility.read_config(u'saveas', u'downloadconfig'): DefaultDownloadStartupConfig.getInstance().set_dest_dir( self.utility.read_config(u'saveas', u'downloadconfig')) self.utility.set_app(self) self.utility.set_session(session) self.guiUtility = GUIUtility.getInstance(self.utility, self.params, self) GUIDBProducer.getInstance() # Broadcast that the initialisation is starting for the splash gauge and those who are interested self.utility.session.notifier.notify(NTFY_STARTUP_TICK, NTFY_CREATE, None, None) session.notifier.notify(NTFY_STARTUP_TICK, NTFY_INSERT, None, 'Starting API') wx.Yield() self._logger.info('Tribler Version: %s Build: %s', version_id, commit_id) version_info = self.utility.read_config('version_info') if version_info.get('version_id', None) != version_id: # First run of a different version version_info['first_run'] = int(time()) version_info['version_id'] = version_id self.utility.write_config('version_info', version_info) session.notifier.notify( NTFY_STARTUP_TICK, NTFY_INSERT, None, 'Starting session and upgrading database (it may take a while)' ) wx.Yield() session.start() self.dispersy = session.lm.dispersy self.dispersy.attach_progress_handler(self.progressHandler) session.notifier.notify(NTFY_STARTUP_TICK, NTFY_INSERT, None, 'Initializing Family Filter') wx.Yield() cat = session.lm.category state = self.utility.read_config('family_filter') if state in (1, 0): cat.set_family_filter(state == 1) else: self.utility.write_config('family_filter', 1) self.utility.flush_config() cat.set_family_filter(True) # Create global speed limits session.notifier.notify(NTFY_STARTUP_TICK, NTFY_INSERT, None, 'Setting up speed limits') wx.Yield() # Counter to suppress some event from occurring self.ratestatecallbackcount = 0 maxup = self.utility.read_config('maxuploadrate') maxdown = self.utility.read_config('maxdownloadrate') # set speed limits using LibtorrentMgr session.set_max_upload_speed(maxup) session.set_max_download_speed(maxdown) # Only allow updates to come in after we defined ratelimiter self.prevActiveDownloads = [] session.set_download_states_callback(self.sesscb_states_callback) # Schedule task for checkpointing Session, to avoid hash checks after # crashes. self.register_task("checkpoint_loop", LoopingCall(self.guiservthread_checkpoint_timer))\ .start(SESSION_CHECKPOINT_INTERVAL, now=False) session.notifier.notify(NTFY_STARTUP_TICK, NTFY_INSERT, None, 'GUIUtility register') wx.Yield() self.guiUtility.register() self.frame = MainFrame(self, None, False) self.frame.SetIcon( wx.Icon( os.path.join(self.installdir, 'Tribler', 'Main', 'vwxGUI', 'images', 'tribler.ico'), wx.BITMAP_TYPE_ICO)) # Arno, 2011-06-15: VLC 1.1.10 pops up separate win, don't have two. self.frame.videoframe = None if sys.platform == 'win32': wx.CallAfter(self.frame.top_bg.Refresh) wx.CallAfter(self.frame.top_bg.Layout) else: self.frame.top_bg.Layout() # Arno, 2007-05-03: wxWidgets 2.8.3.0 and earlier have the MIME-type for .bmp # files set to 'image/x-bmp' whereas 'image/bmp' is the official one. try: bmphand = None hands = wx.Image.GetHandlers() for hand in hands: if hand.GetMimeType() == 'image/x-bmp': bmphand = hand break # wx.Image.AddHandler() if bmphand is not None: bmphand.SetMimeType('image/bmp') except: # wx < 2.7 don't like wx.Image.GetHandlers() print_exc() session.notifier.notify(NTFY_STARTUP_TICK, NTFY_DELETE, None, None) wx.Yield() self.frame.Show(True) self.register_task('free_space_check', LoopingCall(self.guiservthread_free_space_check))\ .start(FREE_SPACE_CHECK_INTERVAL) self.webUI = None if self.utility.read_config('use_webui'): try: from Tribler.Main.webUI.webUI import WebUI self.webUI = WebUI.getInstance( self.guiUtility.library_manager, self.guiUtility.torrentsearch_manager, self.utility.read_config('webui_port')) self.webUI.start() except Exception: print_exc() self.emercoin_mgr = None try: from Tribler.Main.Emercoin.EmercoinMgr import EmercoinMgr self.emercoin_mgr = EmercoinMgr(self.utility) except Exception: print_exc() wx.CallAfter(self.PostInit2) # 08/02/10 Boudewijn: Working from home though console # doesn't allow me to press close. The statement below # gracefully closes Tribler after 120 seconds. # wx.CallLater(120*1000, wx.GetApp().Exit) self.ready = True except Exception as e: session.notifier.notify(NTFY_STARTUP_TICK, NTFY_DELETE, None, None) self.onError(e)
def _upgradeVersion(self, my_version, latest_version, info): # check if there is a .torrent for our OS torrent_key = "torrent-%s" % sys.platform notes_key = "notes-txt-%s" % sys.platform if torrent_key in info: self._logger.info("-- Upgrade %s -> %s", my_version, latest_version) notes = [] if "notes-txt" in info: notes.append(info["notes-txt"]) if notes_key in info: notes.append(info[notes_key]) notes = "\n".join(notes) if notes: for line in notes.split("\n"): self._logger.info("-- Notes: %s", line) else: notes = "No release notes found" self._logger.info("-- Downloading %s for upgrade", info[torrent_key]) # prepare directory and .torrent file location = os.path.join(self.utility.session.get_state_dir(), "upgrade") if not os.path.exists(location): os.mkdir(location) self._logger.info("-- Dir: %s", location) filename = os.path.join( location, os.path.basename(urlparse.urlparse(info[torrent_key])[2])) self._logger.info("-- File: %s", filename) if not os.path.exists(filename): urllib.urlretrieve(info[torrent_key], filename) # torrent def tdef = TorrentDef.load(filename) defaultDLConfig = DefaultDownloadStartupConfig.getInstance() dscfg = defaultDLConfig.copy() # figure out what file to start once download is complete files = tdef.get_files_as_unicode() executable = None for file_ in files: if sys.platform == "win32" and file_.endswith(u".exe"): self._logger.info("-- exe: %s", file_) executable = file_ break elif sys.platform == "linux2" and file_.endswith(u".deb"): self._logger.info("-- deb: %s", file_) executable = file_ break elif sys.platform == "darwin" and file_.endswith(u".dmg"): self._logger.info("-- dmg: %s", file_) executable = file_ break if not executable: self._logger.info("-- Abort upgrade: no file found") return # start download try: download = self.utility.session.start_download_from_tdef(tdef) except DuplicateDownloadException: self._logger.error("-- Duplicate download") download = None for random_download in self.utility.session.get_downloads(): if random_download.get_def().get_infohash( ) == tdef.get_infohash(): download = random_download break # continue until download is finished if download: def start_upgrade(): """ Called by python when everything is shutdown. We can now start the downloaded file that will upgrade tribler. """ executable_path = os.path.join(download.get_dest_dir(), executable) if sys.platform == "win32": args = [executable_path] elif sys.platform == "linux2": args = ["gdebi-gtk", executable_path] elif sys.platform == "darwin": args = ["open", executable_path] self._logger.info("-- Tribler closed, starting upgrade") self._logger.info("-- Start: %s", args) subprocess.Popen(args) def wxthread_upgrade(): """ Called on the wx thread when the .torrent file is downloaded. Will ask the user if Tribler can be shutdown for the upgrade now. """ if self.Close(): atexit.register(start_upgrade) else: self.shutdown_and_upgrade_notes = None def state_callback(state): """ Called every n seconds with an update on the .torrent download that we need to upgrade """ self._logger.debug("-- State: %s %s", dlstatus_strings[state.get_status()], state.get_progress()) # todo: does DLSTATUS_STOPPED mean it has completely downloaded? if state.get_status() == DLSTATUS_SEEDING: self.shutdown_and_upgrade_notes = notes wx.CallAfter(wxthread_upgrade) return (0.0, False) return (1.0, False) download.set_state_callback(state_callback)
def InitStage1(self, installdir, autoload_discovery=True, use_torrent_search=True, use_channel_search=True): """ Stage 1 start: pre-start the session to handle upgrade. """ self.gui_image_manager = GuiImageManager.getInstance(installdir) # Start Tribler Session defaultConfig = SessionStartupConfig() state_dir = defaultConfig.get_state_dir() # Switch to the state dir so relative paths can be used (IE, in LevelDB store paths) if not os.path.exists(state_dir): os.makedirs(state_dir) os.chdir(state_dir) cfgfilename = Session.get_default_config_filename(state_dir) self._logger.debug(u"Session config %s", cfgfilename) self.sconfig = SessionStartupConfig.load(cfgfilename) self.sconfig.set_install_dir(self.installdir) if not self.sconfig.get_watch_folder_path(): default_watch_folder_dir = os.path.join(get_home_dir(), u'Downloads', u'TriblerWatchFolder') self.sconfig.set_watch_folder_path(default_watch_folder_dir) if not os.path.exists(default_watch_folder_dir): os.makedirs(default_watch_folder_dir) # TODO(emilon): Do we still want to force limit this? With the new # torrent store it should be pretty fast even with more that that. # Arno, 2010-03-31: Hard upgrade to 50000 torrents collected self.sconfig.set_torrent_collecting_max_torrents(50000) dlcfgfilename = get_default_dscfg_filename( self.sconfig.get_state_dir()) self._logger.debug("main: Download config %s", dlcfgfilename) if os.path.exists(dlcfgfilename): defaultDLConfig = DefaultDownloadStartupConfig.load(dlcfgfilename) else: defaultDLConfig = DefaultDownloadStartupConfig.getInstance() if not defaultDLConfig.get_dest_dir(): defaultDLConfig.set_dest_dir(get_default_dest_dir()) if not os.path.isdir(defaultDLConfig.get_dest_dir()): try: os.makedirs(defaultDLConfig.get_dest_dir()) except: # Could not create directory, ask user to select a different location dlg = wx.DirDialog( None, "Could not find download directory, please select a new location to store your downloads", style=wx.DEFAULT_DIALOG_STYLE) dlg.SetPath(get_default_dest_dir()) if dlg.ShowModal() == wx.ID_OK: new_dest_dir = dlg.GetPath() defaultDLConfig.set_dest_dir(new_dest_dir) defaultDLConfig.save(dlcfgfilename) self.sconfig.save(cfgfilename) else: # Quit self.onError = lambda e: self._logger.error( "tribler: quitting due to non-existing destination directory" ) raise Exception() if not use_torrent_search: self.sconfig.set_enable_torrent_search(False) if not use_channel_search: self.sconfig.set_enable_channel_search(False) session = Session(self.sconfig, autoload_discovery=autoload_discovery) session.add_observer(self.show_upgrade_dialog, NTFY_UPGRADER, [NTFY_STARTED]) while not session.upgrader.is_done: wx.SafeYield() sleep(0.1) return session
def __init__(self, parent, frame, libraryTorrents=None): wx.Dialog.__init__(self, parent, -1, 'Add an external .torrent', size=(500, 200), name="AddTorrentDialog") self.frame = frame self.guiutility = GUIUtility.getInstance() self.toChannel = libraryTorrents is not None self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance() vSizer = wx.BoxSizer(wx.VERTICAL) firstLine = wx.StaticText( self, -1, 'Please use one of the provided methods to import an external .torrent' ) vSizer.Add(firstLine, 0, wx.EXPAND | wx.BOTTOM, 3) vSizer.AddSpacer((-1, 25)) header = wx.StaticText(self, -1, 'Browse for local .torrent file or files') _set_font(header, fontweight=wx.FONTWEIGHT_BOLD) vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM, 3) vSizer.Add( wx.StaticText( self, -1, 'Use this option if you have downloaded a .torrent manually'), 0, wx.BOTTOM, 3) browseButton = wx.Button(self, -1, 'Browse') browseButton.Bind(wx.EVT_BUTTON, self.OnBrowse) browseDirectory = wx.Button(self, -1, 'Browse for Directory') browseDirectory.Bind(wx.EVT_BUTTON, self.OnBrowseDir) hSizer = wx.BoxSizer(wx.HORIZONTAL) hSizer.Add(browseButton, 0, wx.RIGHT, 3) hSizer.Add(browseDirectory) vSizer.Add(hSizer, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 3) vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.BOTTOM, 10) header = wx.StaticText(self, -1, 'Url') _set_font(header, fontweight=wx.FONTWEIGHT_BOLD) vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 3) vSizer.Add( wx.StaticText( self, -1, 'This could either be a http, magnet, emc, or file link'), 0, wx.BOTTOM, 3) hSizer = wx.BoxSizer(wx.HORIZONTAL) self.magnet = wx.TextCtrl(self, -1) hSizer.Add(self.magnet, 1, wx.ALIGN_CENTER_VERTICAL) linkButton = wx.Button(self, -1, "Add") linkButton.Bind(wx.EVT_BUTTON, self.OnAdd) hSizer.Add(linkButton, 0, wx.LEFT, 3) vSizer.Add(hSizer, 0, wx.EXPAND | wx.BOTTOM, 3) vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.BOTTOM, 10) if libraryTorrents is not None: if len(libraryTorrents) > 0: header = wx.StaticText(self, -1, 'Choose one from your library') _set_font(header, fontweight=wx.FONTWEIGHT_BOLD) vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 3) torrentNames = [torrent.name for torrent in libraryTorrents] hSizer = wx.BoxSizer(wx.HORIZONTAL) self.libraryChoice = wx.Choice(self, -1, choices=torrentNames) self.libraryChoice.torrents = libraryTorrents hSizer.Add(self.libraryChoice, 1, wx.ALIGN_CENTER_VERTICAL) linkButton = wx.Button(self, -1, "Add") linkButton.Bind(wx.EVT_BUTTON, self.OnLibrary) hSizer.Add(linkButton, 0, wx.LEFT, 3) vSizer.Add(hSizer, 0, wx.EXPAND | wx.BOTTOM, 3) vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.BOTTOM, 10) header = wx.StaticText(self, -1, 'Create your own .torrents') _set_font(header, fontweight=wx.FONTWEIGHT_BOLD) vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 3) vSizer.Add(wx.StaticText(self, -1, 'Using your own local files'), 0, wx.BOTTOM, 3) create = wx.Button(self, -1, 'Create') create.Bind(wx.EVT_BUTTON, self.OnCreate) vSizer.Add(create, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 3) sizer = wx.BoxSizer() sizer.Add(vSizer, 1, wx.EXPAND | wx.ALL, 10) self.SetSizerAndFit(sizer)
def startDownload(self, torrentfilename=None, destdir=None, infohash=None, tdef=None, cmdline=False, vodmode=False, hops=0, selectedFiles=None, hidden=False): self._logger.debug(u"startDownload: %s %s %s %s %s", torrentfilename, destdir, tdef, vodmode, selectedFiles) # TODO(lipu): remove the assertions after it becomes stable if infohash is not None: assert isinstance(infohash, str), "infohash type: %s" % type(infohash) assert len(infohash) == 20, "infohash length is not 20: %s, %s" % ( len(infohash), infohash) # the priority of the parameters is: (1) tdef, (2) infohash, (3) torrent_file. # so if we have tdef, infohash and torrent_file will be ignored, and so on. if tdef is None: if infohash is not None: # try to get the torrent from torrent_store if the infohash is provided torrent_data = self.utility.session.get_collected_torrent( infohash) if torrent_data is not None: # use this torrent data for downloading tdef = TorrentDef.load_from_memory(torrent_data) if tdef is None: assert torrentfilename is not None, "torrent file must be provided if tdef and infohash are not given" # try to get the torrent from the given torrent file torrent_data = fix_torrent(torrentfilename) if torrent_data is None: # show error message: could not open torrent file dlg = wx.MessageBox( self, "Could not open torrent file %s" % torrentfilename, "Error", wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return tdef = TorrentDef.load_from_memory(torrent_data) assert tdef is not None, "tdef MUST not be None after loading torrent" try: d = self.utility.session.get_download(tdef.get_infohash()) if d: new_trackers = list( set(tdef.get_trackers_as_single_tuple()) - set(d.get_def().get_trackers_as_single_tuple())) if not new_trackers: raise DuplicateDownloadException() else: @forceWxThread def do_gui(): # Show update tracker dialog dialog = wx.MessageDialog( None, 'This torrent is already being downloaded. Do you wish to load the trackers from it?', 'Tribler', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if dialog.ShowModal() == wx.ID_YES: # Update trackers self.utility.session.update_trackers( tdef.get_infohash(), new_trackers) dialog.Destroy() do_gui() return defaultDLConfig = DefaultDownloadStartupConfig.getInstance() dscfg = defaultDLConfig.copy() cancelDownload = False useDefault = not self.utility.read_config('showsaveas') safe_seeding = self.utility.read_config( 'default_safeseeding_enabled') if not useDefault and not destdir: defaultname = tdef.get_name_as_unicode( ) if tdef.is_multifile_torrent() else None if wx.Thread_IsMain(): dlg = SaveAs(None, tdef, dscfg.get_dest_dir(), defaultname, selectedFiles) dlg.CenterOnParent() if isinstance(tdef, TorrentDefNoMetainfo): # Correct for the smaller size of the dialog if there is no metainfo center_pos = dlg.GetPosition() center_pos[1] -= 150 dlg.SetPosition(center_pos) if dlg.ShowModal() == wx.ID_OK: # If the dialog has collected a torrent, use the new tdef tdef = dlg.GetCollected() or tdef if tdef and tdef.is_multifile_torrent(): selectedFiles = dlg.GetSelectedFiles() destdir = dlg.GetPath() # Anonymity over exit nodes or hidden services safe_seeding = dlg.UseSafeSeeding() if dlg.UseTunnels(): hops = self.utility.read_config( 'default_number_hops') else: cancelDownload = True dlg.Destroy() else: raise Exception("cannot create dialog, not on wx thread") # use default setup else: if useDefault: if self.utility.read_config('default_anonymity_enabled'): # only load default anonymous level if we use default settings hops = self.utility.read_config('default_number_hops') else: hops = 0 if hops > 0: if not tdef: raise Exception( 'Currently only torrents can be downloaded in anonymous mode' ) dscfg.set_hops(hops) dscfg.set_safe_seeding(safe_seeding) if not cancelDownload: if destdir is not None: dscfg.set_dest_dir(destdir) if selectedFiles and len(selectedFiles) == 1: # we should filter files to see if they are all playable videofiles = selectedFiles elif tdef and not selectedFiles: videofiles = tdef.get_files(exts=videoextdefaults) else: videofiles = [] # disable vodmode if no videofiles, unless we still need to collect the torrent if vodmode and len(videofiles) == 0 and ( not tdef or not isinstance(tdef, TorrentDefNoMetainfo)): vodmode = False if vodmode: self._logger.info( 'MainFrame: startDownload: Starting in VOD mode') result = self.utility.session.start_download_from_tdef( tdef, dscfg) self.guiUtility.library_manager.playTorrent( tdef.get_infohash(), videofiles[0] if len(videofiles) == 1 else None) else: if selectedFiles: dscfg.set_selected_files(selectedFiles) self._logger.debug( 'MainFrame: startDownload: Starting in DL mode') result = self.utility.session.start_download_from_tdef( tdef, dscfg, hidden=hidden) if result and not hidden: self.show_saved(tdef) return result except DuplicateDownloadException as e: # If there is something on the cmdline, all other torrents start # in STOPPED state. Restart if cmdline: dlist = self.utility.session.get_downloads() for d in dlist: if d.get_def().get_infohash() == tdef.get_infohash(): d.restart() break if wx.Thread_IsMain(): # show nice warning dialog dlg = wx.MessageDialog( None, "You are already downloading this torrent, see the Downloads section.", "Duplicate download", wx.OK | wx.ICON_ERROR) result = dlg.ShowModal() dlg.Destroy() else: print_exc() self.onWarning(e) except Exception as e: print_exc() self.onWarning(e) return None
def OnExit(self): self.utility.session.notifier.notify(NTFY_CLOSE_TICK, NTFY_CREATE, None, None) blockingCallFromThread(reactor, self.cancel_all_pending_tasks) if self.i2i_server: self.i2i_server.stop() self._logger.info("main: ONEXIT") self.ready = False self.done = True # write all persistent data to disk self.utility.session.notifier.notify( NTFY_CLOSE_TICK, NTFY_INSERT, None, 'Write all persistent data to disk') wx.Yield() if self.webUI: self.webUI.stop() self.webUI.delInstance() if self.frame: self.frame.Destroy() self.frame = None # Don't checkpoint, interferes with current way of saving Preferences, # see Tribler/Main/Dialogs/abcoption.py if self.utility: # Niels: lets add a max waiting time for this session shutdown. session_shutdown_start = time() # TODO(emilon): probably more notification callbacks should be remmoved # here s = self.utility.session s.remove_observer(self.sesscb_ntfy_newversion) s.remove_observer(self.sesscb_ntfy_corrupt_torrent) s.remove_observer(self.sesscb_ntfy_magnet) s.remove_observer(self.sesscb_ntfy_torrentfinished) s.remove_observer(self.sesscb_ntfy_markingupdates) s.remove_observer(self.sesscb_ntfy_moderationupdats) s.remove_observer(self.sesscb_ntfy_modificationupdates) s.remove_observer(self.sesscb_ntfy_commentupdates) s.remove_observer(self.sesscb_ntfy_playlistupdates) s.remove_observer(self.sesscb_ntfy_torrentupdates) s.remove_observer(self.sesscb_ntfy_myprefupdates) s.remove_observer(self.sesscb_ntfy_channelupdates) s.remove_observer(self.sesscb_ntfy_channelupdates) s.remove_observer(self.sesscb_ntfy_activities) s.remove_observer(self.sesscb_ntfy_reachable) try: self._logger.info("ONEXIT cleaning database") self.utility.session.notifier.notify(NTFY_CLOSE_TICK, NTFY_INSERT, None, 'Cleaning database') wx.Yield() torrent_db = self.utility.session.open_dbhandler(NTFY_TORRENTS) torrent_db._db.clean_db(randint(0, 24) == 0, exiting=True) except: print_exc() self.utility.session.notifier.notify(NTFY_CLOSE_TICK, NTFY_INSERT, None, 'Shutdown session') wx.Yield() self.utility.session.shutdown(hacksessconfcheckpoint=False) # Arno, 2012-07-12: Shutdown should be quick # Niels, 2013-03-21: However, setting it too low will prevent checkpoints from being written to disk waittime = 60 while not self.utility.session.has_shutdown(): diff = time() - session_shutdown_start if diff > waittime: self._logger.info( "main: ONEXIT NOT Waiting for Session to shutdown, took too long" ) break self._logger.info( "ONEXIT Waiting for Session to shutdown, will wait for an additional %d seconds", waittime - diff) sleep(3) self._logger.info("ONEXIT Session is shutdown") self.utility.session.notifier.notify(NTFY_CLOSE_TICK, NTFY_INSERT, None, 'Deleting instances') self._logger.debug("ONEXIT deleting instances") Session.del_instance() GUIDBProducer.delInstance() DefaultDownloadStartupConfig.delInstance() GuiImageManager.delInstance() self.utility.session.notifier.notify(NTFY_CLOSE_TICK, NTFY_INSERT, None, 'Exiting now') self.utility.session.notifier.notify(NTFY_CLOSE_TICK, NTFY_DELETE, None, None) GUIUtility.delInstance()