def __init__(self, stdscr, encoding=None): self.formatted_rows = None self.torrent_names = None self.cursel = 1 self.curoff = 1 # TODO: this should really be 0 indexed self.column_string = "" self.popup = None self.messages = deque() self.marked = [] self.last_mark = -1 self._sorted_ids = None self._go_top = False self._curr_filter = None self.entering_search = False self.search_string = None self.cursor = 0 self.coreconfig = component.get("ConsoleUI").coreconfig self.legacy_mode = None self.__status_dict = {} self.__torrent_info_id = None BaseMode.__init__(self, stdscr, encoding) component.Component.__init__(self, "AllTorrents", 1, depend=["SessionProxy"]) curses.curs_set(0) self.stdscr.notimeout(0) self.__split_help() self.update_config() component.start(["AllTorrents"]) self._info_fields = [ ("Name",None,("name",)), ("State", None, ("state",)), ("Down Speed", format_utils.format_speed, ("download_payload_rate",)), ("Up Speed", format_utils.format_speed, ("upload_payload_rate",)), ("Progress", format_utils.format_progress, ("progress",)), ("ETA", deluge.common.ftime, ("eta",)), ("Path", None, ("save_path",)), ("Downloaded",deluge.common.fsize,("all_time_download",)), ("Uploaded", deluge.common.fsize,("total_uploaded",)), ("Share Ratio", format_utils.format_float, ("ratio",)), ("Seeders",format_utils.format_seeds_peers,("num_seeds","total_seeds")), ("Peers",format_utils.format_seeds_peers,("num_peers","total_peers")), ("Active Time",deluge.common.ftime,("active_time",)), ("Seeding Time",deluge.common.ftime,("seeding_time",)), ("Date Added",deluge.common.fdate,("time_added",)), ("Availability", format_utils.format_float, ("distributed_copies",)), ("Pieces", format_utils.format_pieces, ("num_pieces","piece_length")), ] self.__status_keys = ["name","state","download_payload_rate","upload_payload_rate", "progress","eta","all_time_download","total_uploaded", "ratio", "num_seeds","total_seeds","num_peers","total_peers", "active_time", "seeding_time","time_added","distributed_copies", "num_pieces", "piece_length","save_path"]
def enable_plugin(self, plugin_name): """Enables a plugin""" if plugin_name not in self.available_plugins: log.warning("Cannot enable non-existant plugin %s", plugin_name) return if plugin_name in self.plugins: log.warning("Cannot enable already enabled plugin %s", plugin_name) return plugin_name = plugin_name.replace(" ", "-") egg = self.pkg_env[plugin_name][0] egg.activate() for name in egg.get_entry_map(self.entry_name): entry_point = egg.get_entry_info(self.entry_name, name) try: cls = entry_point.load() instance = cls(plugin_name.replace("-", "_")) except Exception, e: log.error("Unable to instantiate plugin!") log.exception(e) continue instance.enable() if self._component_state == "Started": component.start([instance.plugin._component_name]) plugin_name = plugin_name.replace("-", " ") self.plugins[plugin_name] = instance if plugin_name not in self.config["enabled_plugins"]: log.debug("Adding %s to enabled_plugins list in config", plugin_name) self.config["enabled_plugins"].append(plugin_name) log.info("Plugin %s enabled..", plugin_name)
def start(self): """Start the plugin manager""" # Update the enabled_plugins from the core client.core.get_enabled_plugins().addCallback( self._on_get_enabled_plugins) for instance in self.plugins.values(): component.start([instance.plugin._component_name])
def start(self): # Register the daemon and the core RPCs self.rpcserver.register_object(self.core) self.rpcserver.register_object(self) # Make sure we start the PreferencesManager first component.start('PreferencesManager') if not self.standalone: log.info('Deluge daemon starting...') # Create pid file to track if deluged is running, also includes the port number. pid = os.getpid() log.debug('Storing pid %s & port %s in: %s', pid, self.port, self.pid_file) with open(self.pid_file, 'w') as _file: _file.write('%s;%s\n' % (pid, self.port)) component.start() try: reactor.run() finally: log.debug('Remove pid file: %s', self.pid_file) os.remove(self.pid_file) log.info('Deluge daemon shutdown successfully')
def __init__(self, alltorrentmode, torrentid, stdscr, console_config, encoding=None): self.console_config = console_config self.alltorrentmode = alltorrentmode self.torrentid = torrentid self.torrent_state = None self.popup = None self.messages = deque() self._status_keys = [ "files", "name", "state", "download_payload_rate", "upload_payload_rate", "progress", "eta", "all_time_download", "total_uploaded", "ratio", "num_seeds", "total_seeds", "num_peers", "total_peers", "active_time", "seeding_time", "time_added", "distributed_copies", "num_pieces", "piece_length", "save_path", "file_progress", "file_priorities", "message", "total_wanted", "tracker_host", "owner" ] self.file_list = None self.current_file = None self.current_file_idx = 0 self.file_limit = maxint self.file_off = 0 self.more_to_draw = False self.full_names = None self.column_string = "" self.files_sep = None self.marked = {} BaseMode.__init__(self, stdscr, encoding) component.Component.__init__(self, "TorrentDetail", 1, depend=["SessionProxy"]) self.column_names = ["Filename", "Size", "Progress", "Priority"] self.__update_columns() component.start(["TorrentDetail"]) self._listing_start = self.rows // 2 self._listing_space = self._listing_start - self._listing_start client.register_event_handler("TorrentFileRenamedEvent", self._on_torrentfilerenamed_event) client.register_event_handler("TorrentFolderRenamedEvent", self._on_torrentfolderrenamed_event) client.register_event_handler("TorrentRemovedEvent", self._on_torrentremoved_event) curses.curs_set(0) self.stdscr.notimeout(0)
def start_components(self): def on_started(result): component.pause(['TorrentList', 'EventView', 'AddTorrents', 'TorrentDetail', 'Preferences']) if self.interactive: d = component.start().addCallback(on_started) else: d = component.start(['SessionProxy', 'ConsoleUI', 'CoreConfig']) return d
def enable(self): log.info("Enabling MediaInfo Core plugin") self._config = deluge.configmanager.ConfigManager( 'mediainfo.conf', DEFAULT_PREFS) self._core = component.get('Core') self._plugin = component.get('CorePluginManager') self._torrent_id = None self._media_info = {} component.start([self._component_name])
def _on_reactor_start(self): log.debug('_on_reactor_start') self.mainwindow.first_show() if not self.config['standalone']: return self._start_thinclient() err_msg = '' try: client.start_standalone() except DaemonRunningError: err_msg = _( 'A Deluge daemon (deluged) is already running.\n' 'To use Standalone mode, stop local daemon and restart Deluge.' ) except LibtorrentImportError as ex: if 'libtorrent library not found' in str(ex): err_msg = _( 'Only Thin Client mode is available because libtorrent is not installed.\n' 'To use Standalone mode, please install libtorrent package.' ) else: log.exception(ex) err_msg = _( 'Only Thin Client mode is available due to libtorrent import error: %s\n' 'To use Standalone mode, please see logs for error details.' % (str(ex))) except ImportError as ex: log.exception(ex) err_msg = _( 'Only Thin Client mode is available due to unknown Import Error.\n' 'To use Standalone mode, please see logs for error details.') except Exception as ex: log.exception(ex) err_msg = _( 'Only Thin Client mode is available due to unknown Import Error.\n' 'To use Standalone mode, please see logs for error details.') else: component.start() return def on_dialog_response(response): """User response to switching mode dialog.""" if response == ResponseType.YES: # Turning off standalone self.config['standalone'] = False self._start_thinclient() else: # User want keep Standalone Mode so just quit. self.mainwindow.quit() # An error occurred so ask user to switch from Standalone to Thin Client mode. err_msg += '\n\n' + _('Continue in Thin Client mode?') d = YesNoDialog(_('Change User Interface Mode'), err_msg).run() d.addCallback(on_dialog_response)
def __on_connected(self, daemon_info, host_id): if self.gtkui_config["autoconnect"]: self.gtkui_config["autoconnect_host_id"] = host_id if self.running: # When connected to a client, and then trying to connect to another, # this component will be stopped(while the connect deferred is # running), so, self.connection_manager will be deleted. # If that's not the case, close the dialog. self.connection_manager.response(gtk.RESPONSE_OK) component.start()
def __init__(self, alltorrentmode, torrentid, stdscr, encoding=None): self.alltorrentmode = alltorrentmode self.torrentid = torrentid self.torrent_state = None self.popup = None self.messages = deque() self._status_keys = ["files", "name","state","download_payload_rate","upload_payload_rate", "progress","eta","all_time_download","total_uploaded", "ratio", "num_seeds","total_seeds","num_peers","total_peers", "active_time", "seeding_time","time_added","distributed_copies", "num_pieces", "piece_length","save_path","file_progress","file_priorities","message"] self._info_fields = [ ("Name",None,("name",)), ("State", None, ("state",)), ("Status",None,("message",)), ("Down Speed", format_utils.format_speed, ("download_payload_rate",)), ("Up Speed", format_utils.format_speed, ("upload_payload_rate",)), ("Progress", format_utils.format_progress, ("progress",)), ("ETA", deluge.common.ftime, ("eta",)), ("Path", None, ("save_path",)), ("Downloaded",deluge.common.fsize,("all_time_download",)), ("Uploaded", deluge.common.fsize,("total_uploaded",)), ("Share Ratio", lambda x:x < 0 and "∞" or "%.3f"%x, ("ratio",)), ("Seeders",format_utils.format_seeds_peers,("num_seeds","total_seeds")), ("Peers",format_utils.format_seeds_peers,("num_peers","total_peers")), ("Active Time",deluge.common.ftime,("active_time",)), ("Seeding Time",deluge.common.ftime,("seeding_time",)), ("Date Added",deluge.common.fdate,("time_added",)), ("Availability", lambda x:x < 0 and "∞" or "%.3f"%x, ("distributed_copies",)), ("Pieces", format_utils.format_pieces, ("num_pieces","piece_length")), ] self.file_list = None self.current_file = None self.current_file_idx = 0 self.file_limit = maxint self.file_off = 0 self.more_to_draw = False self.column_string = "" self.files_sep = None self.marked = {} BaseMode.__init__(self, stdscr, encoding) component.Component.__init__(self, "TorrentDetail", 1, depend=["SessionProxy"]) self.__split_help() self.column_names = ["Filename", "Size", "Progress", "Priority"] self.__update_columns() component.start(["TorrentDetail"]) curses.curs_set(0) self.stdscr.notimeout(0)
def _on_connect(self, daemon_info, host_id): log.debug('Connected to daemon: %s', host_id) if self.gtkui_config['autoconnect']: self.gtkui_config['autoconnect_host_id'] = host_id if self.running: # When connected to a client, and then trying to connect to another, # this component will be stopped(while the connect deferred is # running), so, self.connection_manager will be deleted. # If that's not the case, close the dialog. self.connection_manager.response(Gtk.ResponseType.OK) component.start()
def start_components(self): def on_started(result): component.pause([ 'TorrentList', 'EventView', 'AddTorrents', 'TorrentDetail', 'Preferences' ]) if self.interactive: d = component.start().addCallback(on_started) else: d = component.start(['SessionProxy', 'ConsoleUI', 'CoreConfig']) return d
def connect(self, host, autostart=False): if autostart and host[1] in ("127.0.0.1", "localhost"): if self.start_daemon(host): for try_counter in range(6, -1, -1): try: yield client.connect(*host[1:]) component.start() except Exception: log.exception("Connection to host failed.") import time time.sleep(0.5) # XXX: twisted timers anyone? if try_counter: log.info("Retrying connection.. Retries left: %s", try_counter) else: yield client.connect(*host[1:]) component.start()
def set_up(self): self.set_unittest_maxdiff(None) self.rpcserver = RPCServer(listen=False) self.rpcserver.factory.protocol = DelugeRPCProtocolTester self.factory = self.rpcserver.factory self.session_id = '0' self.request_id = 11 self.protocol = self.rpcserver.factory.protocol(self.session_id) self.protocol.factory = self.factory self.factory.session_protocols[self.session_id] = self.protocol self.factory.interested_events[self.session_id] = [ 'TorrentFolderRenamedEvent' ] self.protocol.sessionno = self.session_id self.factory.authorized_sessions[ self.session_id] = self.protocol.AuthLevel( rpcserver.AUTH_LEVEL_DEFAULT, '') self.config = test_common.get_test_config() self.core = Core("test") # Must call enable to create the RSSFeedScheduler in core self.core.enable(config=self.config) self.rpcserver.register_object(self.core) return component.start()
def set_up(self): self.setup_config() RPCServer(listen=False) self.core = Core() self.session = lt.session() self.torrent = None return component.start()
def set_mode(self, mode_name, refresh=False): log.debug('Setting console mode: %s', mode_name) mode = self.modes.get(mode_name, None) if mode is None: log.error('Non-existent mode requested: %s', mode_name) return self.stdscr.erase() if self.active_mode: self.active_mode.pause() d = component.pause([self.active_mode.mode_name]) def on_mode_paused(result, mode, *args): from deluge.ui.console.widgets.popup import PopupsHandler if isinstance(mode, PopupsHandler): if mode.popup is not None: # If popups are not removed, they are still referenced in the memory # which can cause issues as the popup's screen will not be destroyed. # This can lead to the popup border being visible for short periods # while the current modes' screen is repainted. log.error( 'Mode "%s" still has popups available after being paused.' ' Ensure all popups are removed on pause!', mode.popup.title, ) d.addCallback(on_mode_paused, self.active_mode) reactor.removeReader(self.active_mode) self.active_mode = mode self.statusbars.screen = self.active_mode # The Screen object is designed to run as a twisted reader so that it # can use twisted's select poll for non-blocking user input. reactor.addReader(self.active_mode) self.stdscr.clear() if self.active_mode._component_state == 'Stopped': component.start([self.active_mode.mode_name]) else: component.resume([self.active_mode.mode_name]) mode.resume() if refresh: mode.refresh() return mode
def _on_reactor_start(self): log.debug("_on_reactor_start") self.mainwindow.first_show() if self.config["classic_mode"]: def on_dialog_response(response): if response != gtk.RESPONSE_YES: # The user does not want to turn Classic Mode off, so just quit reactor.stop() return # Turning off classic_mode self.config["classic_mode"] = False self.__start_non_classic() try: client.start_classic_mode() except deluge.error.DaemonRunningError: d = dialogs.YesNoDialog( _("Turn off Classic Mode?"), _("It appears that a Deluge daemon process (deluged) is already running.\n\n\ You will either need to stop the daemon or turn off Classic Mode to continue.") ).run() self.started_in_classic = False d.addCallback(on_dialog_response) except Exception, e: import traceback tb = sys.exc_info() ed = dialogs.ErrorDialog( _("Error Starting Core"), _("There was an error starting the core component which is required to run Deluge in Classic Mode.\n\n\ Please see the details below for more information."), details=traceback.format_exc(tb[2])).run() def on_ed_response(response): d = dialogs.YesNoDialog( _("Turn off Classic Mode?"), _("Since there was an error starting in Classic Mode would you like to continue by turning it off?" )).run() self.started_in_classic = False d.addCallback(on_dialog_response) ed.addCallback(on_ed_response) else: component.start() return
def test_start_paused_error(self): ComponentTesterUpdate('test_pause_c1') yield component.start(['test_pause_c1']) yield component.pause(['test_pause_c1']) # Deferreds that fail in component have to error handler which results in # twisted doing a log.err call which causes the test to fail. # Prevent failure by ignoring the exception self._observer._ignoreErrors(component.ComponentException) result = yield component.start() self.assertEqual([(result[0][0], result[0][1].value)], [(defer.FAILURE, component.ComponentException( 'Trying to start component "%s" but it is ' 'not in a stopped state. Current state: %s' % ('test_pause_c1', 'Paused'), ''))])
def __init__(self, alltorrentmode, torrentid, stdscr, console_config, encoding=None): self.console_config = console_config self.alltorrentmode = alltorrentmode self.torrentid = torrentid self.torrent_state = None self.popup = None self.messages = deque() self._status_keys = ["files", "name","state","download_payload_rate","upload_payload_rate", "progress","eta","all_time_download","total_uploaded", "ratio", "num_seeds","total_seeds","num_peers","total_peers", "active_time", "seeding_time","time_added","distributed_copies", "num_pieces", "piece_length","save_path","file_progress","file_priorities","message", "total_wanted", "tracker_host", "owner"] self.file_list = None self.current_file = None self.current_file_idx = 0 self.file_limit = maxint self.file_off = 0 self.more_to_draw = False self.full_names = None self.column_string = "" self.files_sep = None self.marked = {} BaseMode.__init__(self, stdscr, encoding) component.Component.__init__(self, "TorrentDetail", 1, depend=["SessionProxy"]) self.column_names = ["Filename", "Size", "Progress", "Priority"] self.__update_columns() component.start(["TorrentDetail"]) self._listing_start = self.rows // 2 self._listing_space = self._listing_start - self._listing_start client.register_event_handler("TorrentFileRenamedEvent", self._on_torrentfilerenamed_event) client.register_event_handler("TorrentFolderRenamedEvent", self._on_torrentfolderrenamed_event) client.register_event_handler("TorrentRemovedEvent", self._on_torrentremoved_event) curses.curs_set(0) self.stdscr.notimeout(0)
def on_connect(result): def on_started(result): def on_started(result): deferreds = [] # If we have args, lets process them and quit # allow multiple commands split by ";" for arg in args.split(";"): deferreds.append(defer.maybeDeferred(self.do_command, arg.strip())) def on_complete(result): self.do_command("quit") dl = defer.DeferredList(deferreds).addCallback(on_complete) # We need to wait for the rpcs in start() to finish before processing # any of the commands. self.console.started_deferred.addCallback(on_started) component.start().addCallback(on_started)
def setUp(self): self.setup_config() global rpcserver global core rpcserver = RPCServer(listen=False) core = Core() self.session = lt.session() self.torrent = None return component.start()
def test_start_paused_error(self): ComponentTesterUpdate('test_pause_c1') yield component.start(['test_pause_c1']) yield component.pause(['test_pause_c1']) # Deferreds that fail in component have to error handler which results in # twisted doing a log.err call which causes the test to fail. # Prevent failure by ignoring the exception self._observer._ignoreErrors(component.ComponentException) result = yield component.start() self.assertEqual( [(result[0][0], result[0][1].value)], [(defer.FAILURE, component.ComponentException( 'Trying to start component "%s" but it is ' 'not in a stopped state. Current state: %s' % ('test_pause_c1', 'Paused'), ''))])
def test_start_component(self): def on_start(result, c): self.assertEqual(c._component_state, 'Started') self.assertEqual(c.start_count, 1) c = ComponentTester('test_start_c1') d = component.start(['test_start_c1']) d.addCallback(on_start, c) return d
def set_up(self): self.setup_config() self.rpcserver = RPCServer(listen=False) self.core = Core() self.core.config.config['lsd'] = False self.core.config.config['new_release_check'] = False self.session = self.core.session self.torrent = None return component.start()
def start_with_depends(self): c1 = ComponentTesterDelayStart('test_start_all_c1') c2 = ComponentTester('test_start_all_c2', depend=['test_start_all_c4']) c3 = ComponentTesterDelayStart('test_start_all_c3', depend=['test_start_all_c5', 'test_start_all_c1']) c4 = ComponentTester('test_start_all_c4', depend=['test_start_all_c3']) c5 = ComponentTester('test_start_all_c5') d = component.start() return (d, c1, c2, c3, c4, c5)
def set_up(self): common.set_tmp_config_dir() self.rpcserver = RPCServer(listen=False) self.core = Core() self.core.config.config['lsd'] = False self.clock = task.Clock() self.tm = self.core.torrentmanager self.tm.callLater = self.clock.callLater return component.start()
def test_start_component(self): def on_start(result, c): self.assertEquals(c._component_state, "Started") self.assertEquals(c.start_count, 1) c = testcomponent("test_start_c1") d = component.start(["test_start_c1"]) d.addCallback(on_start, c) return d
def set_up(self): common.set_tmp_config_dir() self.rpcserver = RPCServer(listen=False) self.core = Core() self.core.config.config['lsd'] = False self.clock = task.Clock() self.core.torrentmanager.callLater = self.clock.callLater self.listen_port = 51242 return component.start().addCallback(self.start_web_server)
def start_with_depends(self): c1 = testcomponent_delaystart("test_start_all_c1") c2 = testcomponent("test_start_all_c2", depend=["test_start_all_c4"]) c3 = testcomponent_delaystart("test_start_all_c3", depend=["test_start_all_c5", "test_start_all_c1"]) c4 = testcomponent("test_start_all_c4", depend=["test_start_all_c3"]) c5 = testcomponent("test_start_all_c5") d = component.start() return (d, c1, c2, c3, c4, c5)
def on_connect(result): def on_started(result): if not self.interactive: def on_started(result): def do_command(result, cmd): return self.do_command(cmd) d = defer.succeed(None) # If we have commands, lets process them, then quit. for command in commands: d.addCallback(do_command, command) if "quit" not in commands and "exit" not in commands: d.addCallback(do_command, "quit") # We need to wait for the rpcs in start() to finish before processing # any of the commands. self.started_deferred.addCallback(on_started) component.start().addCallback(on_started)
def __init__(self, alltorrentmode, stdscr, console_config, encoding=None): self.console_config = console_config self.alltorrentmode = alltorrentmode self.popup = None self.view_offset = 0 self.cursel = 0 self.marked = set() self.last_mark = -1 path = os.path.expanduser(self.console_config["addtorrents_last_path"]) self.path_stack = ["/"] + path.strip("/").split("/") self.path_stack_pos = len(self.path_stack) self.listing_files = [] self.listing_dirs = [] self.raw_rows = [] self.raw_rows_files = [] self.raw_rows_dirs = [] self.formatted_rows = [] self.sort_column = self.console_config["addtorrents_sort_column"] self.reverse_sort = self.console_config["addtorrents_reverse_sort"] BaseMode.__init__(self, stdscr, encoding) self._listing_space = self.rows - 5 self.__refresh_listing() component.Component.__init__(self, "AddTorrents", 1, depend=["SessionProxy"]) component.start(["AddTorrents"]) curses.curs_set(0) self.stdscr.notimeout(0)
def _on_reactor_start(self): log.debug('_on_reactor_start') self.mainwindow.first_show() if not self.config['standalone']: return self._start_thinclient() err_msg = '' try: client.start_standalone() except DaemonRunningError: err_msg = _('A Deluge daemon (deluged) is already running.\n' 'To use Standalone mode, stop local daemon and restart Deluge.') except ImportError as ex: if 'No module named libtorrent' in ex.message: err_msg = _('Only Thin Client mode is available because libtorrent is not installed.\n' 'To use Standalone mode, please install libtorrent package.') else: log.exception(ex) err_msg = _('Only Thin Client mode is available due to unknown Import Error.\n' 'To use Standalone mode, please see logs for error details.') except Exception as ex: log.exception(ex) err_msg = _('Only Thin Client mode is available due to unknown Import Error.\n' 'To use Standalone mode, please see logs for error details.') else: component.start() return def on_dialog_response(response): """User response to switching mode dialog.""" if response == RESPONSE_YES: # Turning off standalone self.config['standalone'] = False self._start_thinclient() else: # User want keep Standalone Mode so just quit. self.mainwindow.quit() # An error occurred so ask user to switch from Standalone to Thin Client mode. err_msg += '\n\n' + _('Continue in Thin Client mode?') d = YesNoDialog(_('Change User Interface Mode'), err_msg).run() d.addCallback(on_dialog_response)
def test_component_start_error(self): ComponentTesterUpdate('test_pause_c1') yield component.start(['test_pause_c1']) yield component.pause(['test_pause_c1']) test_comp = component.get('test_pause_c1') try: result = self.failureResultOf(test_comp._component_start()) except AttributeError: raise SkipTest('This test requires trial failureResultOf() in Twisted version >= 13') self.assertEqual(result.check(component.ComponentException), component.ComponentException)
def _on_reactor_start(self): log.debug("_on_reactor_start") self.mainwindow.first_show() if self.config["classic_mode"]: def on_dialog_response(response): if response != gtk.RESPONSE_YES: # The user does not want to turn Classic Mode off, so just quit self.mainwindow.quit() return # Turning off classic_mode self.config["classic_mode"] = False self.__start_non_classic() try: client.start_classic_mode() except deluge.error.DaemonRunningError: d = dialogs.YesNoDialog( _("Turn off Classic Mode?"), _("It appears that a Deluge daemon process (deluged) is already running.\n\n\ You will either need to stop the daemon or turn off Classic Mode to continue.")).run() self.started_in_classic = False d.addCallback(on_dialog_response) except Exception, e: import traceback tb = sys.exc_info() ed = dialogs.ErrorDialog( _("Error Starting Core"), _("There was an error starting the core component which is required to run Deluge in Classic Mode.\n\n\ Please see the details below for more information."), details=traceback.format_exc(tb[2])).run() def on_ed_response(response): d = dialogs.YesNoDialog( _("Turn off Classic Mode?"), _("Since there was an error starting in Classic Mode would you like to continue by turning it off?")).run() self.started_in_classic = False d.addCallback(on_dialog_response) ed.addCallback(on_ed_response) else: component.start() return
def set_mode(self, mode_name, refresh=False): log.debug('Setting console mode: %s', mode_name) mode = self.modes.get(mode_name, None) if mode is None: log.error('Non-existent mode requested: %s', mode_name) return self.stdscr.erase() if self.active_mode: self.active_mode.pause() d = component.pause([self.active_mode.mode_name]) def on_mode_paused(result, mode, *args): from deluge.ui.console.widgets.popup import PopupsHandler if isinstance(mode, PopupsHandler): if mode.popup is not None: # If popups are not removed, they are still referenced in the memory # which can cause issues as the popup's screen will not be destroyed. # This can lead to the popup border being visible for short periods # while the current modes' screen is repainted. log.error('Mode "%s" still has popups available after being paused.' ' Ensure all popups are removed on pause!', mode.popup.title) d.addCallback(on_mode_paused, self.active_mode) reactor.removeReader(self.active_mode) self.active_mode = mode self.statusbars.screen = self.active_mode # The Screen object is designed to run as a twisted reader so that it # can use twisted's select poll for non-blocking user input. reactor.addReader(self.active_mode) self.stdscr.clear() if self.active_mode._component_state == 'Stopped': component.start([self.active_mode.mode_name]) else: component.resume([self.active_mode.mode_name]) mode.resume() if refresh: mode.refresh() return mode
def start_with_depends(self): c1 = ComponentTesterDelayStart('test_start_all_c1') c2 = ComponentTester('test_start_all_c2', depend=['test_start_all_c4']) c3 = ComponentTesterDelayStart( 'test_start_all_c3', depend=['test_start_all_c5', 'test_start_all_c1']) c4 = ComponentTester('test_start_all_c4', depend=['test_start_all_c3']) c5 = ComponentTester('test_start_all_c5') d = component.start() return (d, c1, c2, c3, c4, c5)
def start_with_depends(self): c1 = testcomponent_delaystart("test_start_all_c1") c2 = testcomponent("test_start_all_c2", depend=["test_start_all_c4"]) c3 = testcomponent_delaystart( "test_start_all_c3", depend=["test_start_all_c5", "test_start_all_c1"]) c4 = testcomponent("test_start_all_c4", depend=["test_start_all_c3"]) c5 = testcomponent("test_start_all_c5") d = component.start() return (d, c1, c2, c3, c4, c5)
def enable_plugin(self, plugin_name): """Enables a plugin""" if plugin_name not in self.available_plugins: log.warning("Cannot enable non-existant plugin %s", plugin_name) return if plugin_name in self.plugins: log.warning("Cannot enable already enabled plugin %s", plugin_name) return plugin_name = plugin_name.replace(" ", "-") egg = self.pkg_env[plugin_name][0] egg.activate() for name in egg.get_entry_map(self.entry_name): entry_point = egg.get_entry_info(self.entry_name, name) try: cls = entry_point.load() instance = cls(plugin_name.replace("-", "_")) except Exception, e: log.error("Unable to instantiate plugin %r from %r!", name, egg.location) log.exception(e) continue instance.enable() if not instance.__module__.startswith("deluge.plugins."): import warnings warnings.warn_explicit( DEPRECATION_WARNING % name, DeprecationWarning, instance.__module__, 0 ) if self._component_state == "Started": component.start([instance.plugin._component_name]) plugin_name = plugin_name.replace("-", " ") self.plugins[plugin_name] = instance if plugin_name not in self.config["enabled_plugins"]: log.debug("Adding %s to enabled_plugins list in config", plugin_name) self.config["enabled_plugins"].append(plugin_name) log.info("Plugin %s enabled..", plugin_name)
def test_update(self): def on_start(result, c1, counter): self.assertTrue(c1._component_timer) self.assertTrue(c1._component_timer.running) self.assertNotEqual(c1.counter, counter) return component.stop() c1 = testcomponent_update("test_update_c1") cnt = int(c1.counter) d = component.start(["test_update_c1"]) d.addCallback(on_start, c1, cnt) return d
def _on_reactor_start(self): log.debug("_on_reactor_start") self.mainwindow.first_show() if self.config["classic_mode"]: def on_dialog_response(response): if response != Gtk.ResponseType.YES: # The user does not want to turn Classic Mode off, so just quit self.mainwindow.quit() return # Turning off classic_mode self.config["classic_mode"] = False self.__start_non_classic() try: try: client.start_classic_mode() except deluge.error.DaemonRunningError: d = dialogs.YesNoDialog( _("Turn off Classic Mode?"), _("It appears that a Deluge daemon process (deluged) is already running.\n\n\ You will either need to stop the daemon or turn off Classic Mode to continue.") ).run() self.started_in_classic = False d.addCallback(on_dialog_response) except ImportError, e: if "No module named libtorrent" in e.message: d = dialogs.YesNoDialog( _("Enable Thin Client Mode?"), _("Thin client mode is only available because libtorrent is not installed.\n\n\ To use Deluge standalone (Classic mode) please install libtorrent.")).run() self.started_in_classic = False d.addCallback(on_dialog_response) else: raise else: component.start() return
def test_update(self): def on_start(result, c1, counter): self.assertTrue(c1._component_timer) self.assertTrue(c1._component_timer.running) self.assertNotEqual(c1.counter, counter) return component.stop() c1 = ComponentTesterUpdate('test_update_c1') cnt = int(c1.counter) d = component.start(['test_update_c1']) d.addCallback(on_start, c1, cnt) return d
def test_component_start_error(self): ComponentTesterUpdate('test_pause_c1') yield component.start(['test_pause_c1']) yield component.pause(['test_pause_c1']) test_comp = component.get('test_pause_c1') try: result = self.failureResultOf(test_comp._component_start()) except AttributeError: raise SkipTest( 'This test requires trial failureResultOf() in Twisted version >= 13' ) self.assertEqual(result.check(component.ComponentException), component.ComponentException)
def set_up(self): self.rpcserver = RPCServer(listen=False) self.rpcserver.factory.protocol = DelugeRPCProtocolTester self.factory = self.rpcserver.factory self.session_id = '0' self.request_id = 11 self.protocol = self.rpcserver.factory.protocol() self.protocol.factory = self.factory self.protocol.transport = self.protocol self.factory.session_protocols[self.session_id] = self.protocol self.factory.authorized_sessions[self.session_id] = None self.factory.interested_events[self.session_id] = ['TorrentFolderRenamedEvent'] self.protocol.sessionno = self.session_id return component.start()
def test_stop_component(self): def on_stop(result, c): self.assertEquals(c._component_state, "Stopped") self.assertFalse(c._component_timer.running) self.assertEquals(c.stop_count, 1) def on_start(result, c): self.assertEquals(c._component_state, "Started") return component.stop(["test_stop_component_c1"]).addCallback(on_stop, c) c = testcomponent_update("test_stop_component_c1") d = component.start(["test_stop_component_c1"]) d.addCallback(on_start, c) return d
def test_start_depends(self): def on_start(result, c1, c2): self.assertEquals(c1._component_state, "Started") self.assertEquals(c2._component_state, "Started") self.assertEquals(c1.start_count, 1) self.assertEquals(c2.start_count, 1) c1 = testcomponent("test_start_depends_c1") c2 = testcomponent("test_start_depends_c2") c2._component_depend = ["test_start_depends_c1"] d = component.start(["test_start_depends_c2"]) d.addCallback(on_start, c1, c2) return d
def test_stop_component(self): def on_stop(result, c): self.assertEqual(c._component_state, 'Stopped') self.assertFalse(c._component_timer.running) self.assertEqual(c.stop_count, 1) def on_start(result, c): self.assertEqual(c._component_state, 'Started') return component.stop(['test_stop_component_c1']).addCallback(on_stop, c) c = ComponentTesterUpdate('test_stop_component_c1') d = component.start(['test_stop_component_c1']) d.addCallback(on_start, c) return d
def _on_reactor_start(self): log.debug("_on_reactor_start") self.mainwindow.first_show() if self.config["classic_mode"]: def on_dialog_response(response): if response != gtk.RESPONSE_YES: # The user does not want to turn Classic Mode off, so just quit self.mainwindow.quit() return # Turning off classic_mode self.config["classic_mode"] = False self.__start_non_classic() try: try: client.start_classic_mode() except deluge.error.DaemonRunningError: d = dialogs.YesNoDialog( _("Turn off Classic Mode?"), _("It appears that a Deluge daemon process (deluged) is already running.\n\n\ You will either need to stop the daemon or turn off Classic Mode to continue.")).run() self.started_in_classic = False d.addCallback(on_dialog_response) except ImportError, e: if "No module named libtorrent" in e.message: d = dialogs.YesNoDialog( _("Enable Thin Client Mode?"), _("Thin client mode is only available because libtorrent is not installed.\n\n\ To use Deluge standalone (Classic mode) please install libtorrent.")).run() self.started_in_classic = False d.addCallback(on_dialog_response) else: raise else: component.start() return
def setUp(self): """ TODO : Creating a fake environment """ logging.basicConfig(level=logging.DEBUG) (self.serie, self.episode) = tests.common_test.get_serie_and_ep() defe = component.start() defer.gatherResults([defe]) try: os.makedirs(os.path.join(self.serie.get_path_to_serie(), "saison6")) except Exception: pass return
def test_shutdown(self): def on_shutdown(result, c1): self.assertTrue(c1.shutdowned) self.assertEquals(c1._component_state, "Stopped") self.assertEquals(c1.stop_count, 1) def on_start(result, c1): d = component.shutdown() d.addCallback(on_shutdown, c1) return d c1 = testcomponent_shutdown("test_shutdown_c1") d = component.start(["test_shutdown_c1"]) d.addCallback(on_start, c1) return d