当前位置: 首页>>代码示例>>Python>>正文


Python ConfigManager.save方法代码示例

本文整理汇总了Python中deluge.configmanager.ConfigManager.save方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigManager.save方法的具体用法?Python ConfigManager.save怎么用?Python ConfigManager.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在deluge.configmanager.ConfigManager的用法示例。


在下文中一共展示了ConfigManager.save方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Core

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class Core(CorePluginBase):
    def enable(self):
        self.config = ConfigManager('execute.conf', DEFAULT_CONFIG)
        event_manager = component.get('EventManager')
        self.registered_events = {}
        self.preremoved_cache = {}

        # Go through the commands list and register event handlers
        for command in self.config['commands']:
            event = command[EXECUTE_EVENT]
            if event in self.registered_events:
                continue

            def create_event_handler(event):
                def event_handler(torrent_id, *arg):
                    self.execute_commands(torrent_id, event, *arg)
                return event_handler
            event_handler = create_event_handler(event)
            event_manager.register_event_handler(EVENT_MAP[event], event_handler)
            if event == 'removed':
                event_manager.register_event_handler('PreTorrentRemovedEvent', self.on_preremoved)
            self.registered_events[event] = event_handler

        log.debug('Execute core plugin enabled!')

    def on_preremoved(self, torrent_id):
        # Get and store the torrent info before it is removed
        torrent = component.get('TorrentManager').torrents[torrent_id]
        info = torrent.get_status(['name', 'download_location'])
        self.preremoved_cache[torrent_id] = [torrent_id, info['name'], info['download_location']]

    def execute_commands(self, torrent_id, event, *arg):
        if event == 'added' and arg[0]:
            # No futher action as from_state (arg[0]) is True
            return
        elif event == 'removed':
            torrent_id, torrent_name, download_location = self.preremoved_cache.pop(torrent_id)
        else:
            torrent = component.get('TorrentManager').torrents[torrent_id]
            info = torrent.get_status(['name', 'download_location'])
            # Grab the torrent name and download location
            # getProcessOutputAndValue requires args to be str
            torrent_name = info['name']
            download_location = info['download_location']

        log.debug('Running commands for %s', event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn('Command "%s" failed with exit code %d', command, exit_code)
                if stdout:
                    log.warn('stdout: %s', stdout)
                if stderr:
                    log.warn('stderr: %s', stderr)

        # Go through and execute all the commands
        for command in self.config['commands']:
            if command[EXECUTE_EVENT] == event:
                command = os.path.expandvars(command[EXECUTE_COMMAND])
                command = os.path.expanduser(command)

                cmd_args = [torrent_id.encode('utf8'), torrent_name.encode('utf8'),
                            download_location.encode('utf8')]
                if windows_check():
                    # Escape ampersand on windows (see #2784)
                    cmd_args = [cmd_arg.replace('&', '^^^&') for cmd_arg in cmd_args]

                if os.path.isfile(command) and os.access(command, os.X_OK):
                    log.debug('Running %s with args: %s', command, cmd_args)
                    d = getProcessOutputAndValue(command, cmd_args, env=os.environ)
                    d.addCallback(log_error, command)
                else:
                    log.error('Execute script not found or not executable')

    def disable(self):
        self.config.save()
        event_manager = component.get('EventManager')
        for event, handler in self.registered_events.items():
            event_manager.deregister_event_handler(event, handler)
        log.debug('Execute core plugin disabled!')

    # Exported RPC methods #
    @export
    def add_command(self, event, command):
        command_id = hashlib.sha1(str(time.time())).hexdigest()
        self.config['commands'].append((command_id, event, command))
        self.config.save()
        component.get('EventManager').emit(ExecuteCommandAddedEvent(command_id, event, command))

    @export
    def get_commands(self):
        return self.config['commands']

    @export
    def remove_command(self, command_id):
        for command in self.config['commands']:
            if command[EXECUTE_ID] == command_id:
                self.config['commands'].remove(command)
                component.get('EventManager').emit(ExecuteCommandRemovedEvent(command_id))
#.........这里部分代码省略.........
开发者ID:deluge-torrent,项目名称:deluge,代码行数:103,代码来源:core.py

示例2: ConnectionManager

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class ConnectionManager(component.Component):
    def __init__(self):
        component.Component.__init__(self, "ConnectionManager")
        self.gtkui_config = ConfigManager("gtkui.conf")

        self.config = ConfigManager("hostlist.conf.1.2", DEFAULT_CONFIG)

        self.running = False

    # Component overrides
    def start(self):
        pass

    def stop(self):
        # Close this dialog when we are shutting down
        if self.running:
            self.connection_manager.response(gtk.RESPONSE_CLOSE)

    def shutdown(self):
        pass

    # Public methods
    def show(self):
        """
        Show the ConnectionManager dialog.
        """
        # Get the glade file for the connection manager
        self.glade = gtk.glade.XML(
                    pkg_resources.resource_filename("deluge.ui.gtkui",
                                            "glade/connection_manager.glade"))
        self.window = component.get("MainWindow")

        # Setup the ConnectionManager dialog
        self.connection_manager = self.glade.get_widget("connection_manager")
        self.connection_manager.set_transient_for(self.window.window)

        self.connection_manager.set_icon(common.get_deluge_icon())

        self.glade.get_widget("image1").set_from_pixbuf(common.get_logo(32))

        self.hostlist = self.glade.get_widget("hostlist")

        # Create status pixbufs
        if not HOSTLIST_PIXBUFS:
            for stock_id in (gtk.STOCK_NO, gtk.STOCK_YES, gtk.STOCK_CONNECT):
                HOSTLIST_PIXBUFS.append(self.connection_manager.render_icon(stock_id, gtk.ICON_SIZE_MENU))

        # Create the host list gtkliststore
        # id-hash, hostname, port, status, username, password, version
        self.liststore = gtk.ListStore(str, str, int, str, str, str, str)

        # Setup host list treeview
        self.hostlist.set_model(self.liststore)
        render = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn(_("Status"), render)
        column.set_cell_data_func(render, cell_render_status, 3)
        self.hostlist.append_column(column)
        render = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Host"), render, text=HOSTLIST_COL_HOST)
        column.set_cell_data_func(render, cell_render_host, (1, 2, 4))
        column.set_expand(True)
        self.hostlist.append_column(column)
        render = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Version"), render, text=HOSTLIST_COL_VERSION)
        self.hostlist.append_column(column)

        # Load any saved host entries
        self.__load_hostlist()
        self.__load_options()

        # Select the first host if possible
        if len(self.liststore) > 0:
            self.hostlist.get_selection().select_path("0")

        # Connect the signals to the handlers
        self.glade.signal_autoconnect(self)
        self.hostlist.get_selection().connect("changed", self.on_hostlist_selection_changed)

        self.__update_list()

        self.running = True
        response = self.connection_manager.run()
        self.running = False

        # Save the toggle options
        self.__save_options()
        self.__save_hostlist()

        self.connection_manager.destroy()
        del self.glade
        del self.window
        del self.connection_manager
        del self.liststore
        del self.hostlist

    def add_host(self, host, port, username="", password=""):
        """
        Adds a host to the list.

        :param host: str, the hostname
#.........这里部分代码省略.........
开发者ID:laanwj,项目名称:deluge,代码行数:103,代码来源:connectionmanager.py

示例3: Core

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class Core(CorePluginBase):
    def enable(self):
        self.config = ConfigManager("execute.conf", DEFAULT_CONFIG)
        event_manager = component.get("EventManager")
        self.registered_events = {}

        # Go through the commands list and register event handlers
        for command in self.config["commands"]:
            event = command[EXECUTE_EVENT]
            if event in self.registered_events:
                continue

            def create_event_handler(event):
                def event_handler(torrent_id, *arg):
                    self.execute_commands(torrent_id, event, *arg)

                return event_handler

            event_handler = create_event_handler(event)
            event_manager.register_event_handler(EVENT_MAP[event], event_handler)
            self.registered_events[event] = event_handler

        log.debug("Execute core plugin enabled!")

    def execute_commands(self, torrent_id, event, *arg):
        torrent = component.get("TorrentManager").torrents[torrent_id]
        info = torrent.get_status(["name", "save_path", "move_on_completed", "move_on_completed_path"])

        # Grab the torrent name and save path
        torrent_name = info["name"]
        if event == "complete":
            save_path = info["move_on_completed_path"] if info["move_on_completed"] else info["save_path"]
        elif event == "added" and arg[0]:
            # No futher action as from_state (arg[0]) is True
            return
        else:
            save_path = info["save_path"]

        log.debug("[execute] Running commands for %s", event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn("[execute] command '%s' failed with exit code %d", command, exit_code)
                if stdout:
                    log.warn("[execute] stdout: %s", stdout)
                if stderr:
                    log.warn("[execute] stderr: %s", stderr)

        # Go through and execute all the commands
        for command in self.config["commands"]:
            if command[EXECUTE_EVENT] == event:
                command = os.path.expandvars(command[EXECUTE_COMMAND])
                command = os.path.expanduser(command)
                log.debug("[execute] running %s", command)
                d = getProcessOutputAndValue(command, (torrent_id, torrent_name, save_path), env=os.environ)
                d.addCallback(log_error, command)

    def disable(self):
        self.config.save()
        event_manager = component.get("EventManager")
        for event, handler in self.registered_events.iteritems():
            event_manager.deregister_event_handler(event, handler)
        log.debug("Execute core plugin disabled!")

    ### Exported RPC methods ###
    @export
    def add_command(self, event, command):
        command_id = hashlib.sha1(str(time.time())).hexdigest()
        self.config["commands"].append((command_id, event, command))
        self.config.save()
        component.get("EventManager").emit(ExecuteCommandAddedEvent(command_id, event, command))

    @export
    def get_commands(self):
        return self.config["commands"]

    @export
    def remove_command(self, command_id):
        for command in self.config["commands"]:
            if command[EXECUTE_ID] == command_id:
                self.config["commands"].remove(command)
                component.get("EventManager").emit(ExecuteCommandRemovedEvent(command_id))
                break
        self.config.save()

    @export
    def save_command(self, command_id, event, cmd):
        for i, command in enumerate(self.config["commands"]):
            if command[EXECUTE_ID] == command_id:
                self.config["commands"][i] = (command_id, event, cmd)
                break
        self.config.save()
开发者ID:NoGare,项目名称:deluge1,代码行数:95,代码来源:core.py

示例4: GtkUI

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]

#.........这里部分代码省略.........
        self.closing = False

        # Twisted catches signals to terminate, so have it call a pre_shutdown method.
        reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)

        def gtkui_sigint_handler(num, frame):
            log.debug('SIGINT signal caught, firing event: gtkui_close')
            reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')

        signal.signal(signal.SIGINT, gtkui_sigint_handler)

    def start(self):
        reactor.callWhenRunning(self._on_reactor_start)

        # Initialize gdk threading
        threads_enter()
        reactor.run()
        # Reactor no longer running so async callbacks (Deferreds) cannot be
        # processed after this point.
        threads_leave()

    def shutdown(self, *args, **kwargs):
        log.debug('GTKUI shutting down...')
        # Shutdown all components
        if client.is_standalone:
            return component.shutdown()

    @defer.inlineCallbacks
    def close(self):
        if self.closing:
            return
        self.closing = True
        # Make sure the config is saved.
        self.config.save()
        # Ensure columns state is saved
        self.torrentview.save_state()
        # Shut down components
        yield self.shutdown()

        # The gtk modal dialogs (e.g. Preferences) can prevent the application
        # quitting, so force exiting by destroying MainWindow. Must be done here
        # to avoid hanging when quitting with SIGINT (CTRL-C).
        self.mainwindow.window.destroy()

        reactor.stop()

        # Restart the application after closing if MainWindow restart attribute set.
        if component.get('MainWindow').restart:
            os.execv(sys.argv[0], sys.argv)

    def log_rpc_stats(self):
        """Log RPC statistics for thinclient mode."""
        if not client.connected():
            return

        t = time.time()
        recv = client.get_bytes_recv()
        sent = client.get_bytes_sent()
        delta_time = t - self.daemon_bps[0]
        delta_sent = sent - self.daemon_bps[1]
        delta_recv = recv - self.daemon_bps[2]
        self.daemon_bps = (t, sent, recv)
        sent_rate = fspeed(delta_sent / delta_time)
        recv_rate = fspeed(delta_recv / delta_time)
        log.debug('RPC: Sent %s (%s) Recv %s (%s)', fsize(sent), sent_rate, fsize(recv), recv_rate)
开发者ID:deluge-torrent,项目名称:deluge,代码行数:69,代码来源:gtkui.py

示例5: ConnectionManager

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class ConnectionManager(BaseMode):
    def __init__(self, stdscr, encoding=None):
        self.popup = None
        self.statuses = {}
        self.messages = deque()
        self.config = ConfigManager("hostlist.conf.1.2", DEFAULT_CONFIG)
        BaseMode.__init__(self, stdscr, encoding)
        self.__update_statuses()
        self.__update_popup()

    def __update_popup(self):
        self.popup = SelectablePopup(self,"Select Host",self.__host_selected)
        self.popup.add_line("{!white,black,bold!}'Q'=quit, 'r'=refresh, 'a'=add new host, 'D'=delete host",selectable=False)
        for host in self.config["hosts"]:
            if host[0] in self.statuses:
                self.popup.add_line("%s:%d [Online] (%s)"%(host[1],host[2],self.statuses[host[0]]),data=host[0],foreground="green")
            else:
                self.popup.add_line("%s:%d [Offline]"%(host[1],host[2]),data=host[0],foreground="red")
        self.inlist = True
        self.refresh()

    def __update_statuses(self):
        """Updates the host status"""
        def on_connect(result, c, host_id):
            def on_info(info, c):
                self.statuses[host_id] = info
                self.__update_popup()
                c.disconnect()

            def on_info_fail(reason, c):
                if host_id in self.statuses:
                    del self.statuses[host_id]
                c.disconnect()

            d = c.daemon.info()
            d.addCallback(on_info, c)
            d.addErrback(on_info_fail, c)

        def on_connect_failed(reason, host_id):
            if host_id in self.statuses:
                del self.statuses[host_id]

        for host in self.config["hosts"]:
            c = deluge.ui.client.Client()
            hadr = host[1]
            port = host[2]
            user = host[3]
            password = host[4]
            d = c.connect(hadr, port, user, password)
            d.addCallback(on_connect, c, host[0])
            d.addErrback(on_connect_failed, host[0])

    def __on_connected(self,result):
        component.start()
        self.stdscr.erase()
        at = AllTorrents(self.stdscr, self.encoding)
        component.get("ConsoleUI").set_mode(at)
        at.resume()

    def __host_selected(self, idx, data):
        for host in self.config["hosts"]:
            if host[0] == data and host[0] in self.statuses:
                client.connect(host[1], host[2], host[3], host[4]).addCallback(self.__on_connected)
        return False

    def __do_add(self,result):
        hostname = result["hostname"]
        try:
            port = int(result["port"])
        except ValueError:
            self.report_message("Can't add host","Invalid port.  Must be an integer")
            return
        username = result["username"]
        password = result["password"]
        for host in self.config["hosts"]:
            if (host[1],host[2],host[3]) == (hostname, port, username):
                self.report_message("Can't add host","Host already in list")
                return
        newid = hashlib.sha1(str(time.time())).hexdigest()
        self.config["hosts"].append((newid, hostname, port, username, password))
        self.config.save()
        self.__update_popup()

    def __add_popup(self):
        self.inlist = False
        self.popup = InputPopup(self,"Add Host (up & down arrows to navigate, esc to cancel)",close_cb=self.__do_add)
        self.popup.add_text_input("Hostname:","hostname")
        self.popup.add_text_input("Port:","port")
        self.popup.add_text_input("Username:","username")
        self.popup.add_text_input("Password:","password")
        self.refresh()

    def __delete_current_host(self):
        idx,data = self.popup.current_selection()
        log.debug("deleting host: %s",data)
        for host in self.config["hosts"]:
            if host[0] == data:
                self.config["hosts"].remove(host)
                break
        self.config.save()
#.........这里部分代码省略.........
开发者ID:Ashod,项目名称:Deluge,代码行数:103,代码来源:connectionmanager.py

示例6: Core

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class Core(CorePluginBase):
    """
    self.labels = {label_id:label_options_dict}
    self.torrent_labels = {torrent_id:label_id}
    """
    def enable(self):
        log.info("*** Start Label plugin ***")
        self.plugin = component.get("CorePluginManager")
        self.plugin.register_status_field("label", self._status_get_label)

        #__init__
        core = component.get("Core")
        self.config = ConfigManager("label.conf", defaults=CONFIG_DEFAULTS)
        self.core_cfg = ConfigManager("core.conf")

        #reduce typing, assigning some values to self...
        self.torrents = core.torrentmanager.torrents
        self.labels = self.config["labels"]
        self.torrent_labels = self.config["torrent_labels"]

        self.clean_initial_config()

        component.get("EventManager").register_event_handler("TorrentAddedEvent", self.post_torrent_add)
        component.get("EventManager").register_event_handler("TorrentRemovedEvent", self.post_torrent_remove)

        #register tree:
        component.get("FilterManager").register_tree_field("label", self.init_filter_dict)

        log.debug("Label plugin enabled..")

    def disable(self):
        self.plugin.deregister_status_field("label")
        component.get("FilterManager").deregister_tree_field("label")
        component.get("EventManager").deregister_event_handler("TorrentAddedEvent", self.post_torrent_add)
        component.get("EventManager").deregister_event_handler("TorrentRemovedEvent", self.post_torrent_remove)

    def update(self):
        pass

    def init_filter_dict(self):
        return dict( [(label, 0) for label in self.labels.keys()])

    ## Plugin hooks ##
    def post_torrent_add(self, torrent_id, from_state):
        log.debug("post_torrent_add")
        torrent = self.torrents[torrent_id]

        for label_id, options in self.labels.iteritems():
            if options["auto_add"]:
                if self._has_auto_match(torrent, options):
                    self.set_torrent(torrent_id, label_id)
                    return

    def post_torrent_remove(self, torrent_id):
        log.debug("post_torrent_remove")
        if torrent_id in self.torrent_labels:
            del self.torrent_labels[torrent_id]

    ## Utils ##
    def clean_config(self):
        """remove invalid data from config-file"""
        for torrent_id, label_id in list(self.torrent_labels.iteritems()):
            if (not label_id in self.labels) or (not torrent_id in self.torrents):
                log.debug("label: rm %s:%s" % (torrent_id,label_id))
                del self.torrent_labels[torrent_id]

    def clean_initial_config(self):
        """
        *add any new keys in OPTIONS_DEFAULTS
        *set all None values to default <-fix development config
        """
        log.debug(self.labels.keys())
        for key in self.labels.keys():
            options = dict(OPTIONS_DEFAULTS)
            options.update(self.labels[key])
            self.labels[key] = options

        for label, options in self.labels.items():
            for key, value in options.items():
                if value == None:
                    self.labels[label][key] = OPTIONS_DEFAULTS[key]

    def save_config(self):
        self.clean_config()
        self.config.save()

    @export
    def get_labels(self):
        return sorted(self.labels.keys())

    #Labels:
    @export
    def add(self, label_id):
        """add a label
        see label_set_options for more options.
        """
        label_id = label_id.lower()
        CheckInput(RE_VALID.match(label_id) , _("Invalid label, valid characters:[a-z0-9_-]"))
        CheckInput(label_id, _("Empty Label"))
        CheckInput(not (label_id in self.labels) , _("Label already exists"))
#.........这里部分代码省略.........
开发者ID:s0undt3ch,项目名称:Deluge,代码行数:103,代码来源:core.py

示例7: Core

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class Core(CorePluginBase):
    def enable(self):
        self.config = ConfigManager("execute.conf", DEFAULT_CONFIG)
        event_manager = component.get("EventManager")
        self.registered_events = {}

        # Go through the commands list and register event handlers
        for command in self.config["commands"]:
            event = command[EXECUTE_EVENT]
            if event in self.registered_events:
                continue

            def create_event_handler(event):
                def event_handler(torrent_id):
                    self.execute_commands(torrent_id, event)
                return event_handler
            event_handler = create_event_handler(event)
            event_manager.register_event_handler(EVENT_MAP[event], event_handler)
            self.registered_events[event] = event_handler

        log.debug("Execute core plugin enabled!")

    def execute_commands(self, torrent_id, event):
        torrent = component.get("TorrentManager").torrents[torrent_id]
        info = torrent.get_status(["name", "save_path", "move_on_completed", "move_on_completed_path"])

        # Grab the torrent name and save path
        torrent_name = info["name"]
        if event == "complete":
            save_path = info["move_on_completed_path"] if info ["move_on_completed"] else info["save_path"]
        else:
            save_path = info["save_path"]

        log.debug("[execute] Running commands for %s", event)

        # Go through and execute all the commands
        for command in self.config["commands"]:
            if command[EXECUTE_EVENT] == event:
                command = os.path.expandvars(command[EXECUTE_COMMAND])
                command = os.path.expanduser(command)
                log.debug("[execute] running %s", command)
                p = Popen([command, torrent_id, torrent_name, save_path], stdin=PIPE, stdout=PIPE, stderr=PIPE)
                if p.wait() != 0:
                    log.warn("Execute command failed with exit code %d", p.returncode)

    def disable(self):
        self.config.save()
        event_manager = component.get("EventManager")
        for event, handler in self.registered_events.iteritems():
            event_manager.deregister_event_handler(event, handler)
        log.debug("Execute core plugin disabled!")

    ### Exported RPC methods ###
    @export
    def add_command(self, event, command):
        command_id = hashlib.sha1(str(time.time())).hexdigest()
        self.config["commands"].append((command_id, event, command))
        self.config.save()
        component.get("EventManager").emit(ExecuteCommandAddedEvent(command_id, event, command))

    @export
    def get_commands(self):
        return self.config["commands"]

    @export
    def remove_command(self, command_id):
        for command in self.config["commands"]:
            if command[EXECUTE_ID] == command_id:
                self.config["commands"].remove(command)
                component.get("EventManager").emit(ExecuteCommandRemovedEvent(command_id))
                break
        self.config.save()

    @export
    def save_command(self, command_id, event, cmd):
        for i, command in enumerate(self.config["commands"]):
            if command[EXECUTE_ID] == command_id:
                self.config["commands"][i] = (command_id, event, cmd)
                break
        self.config.save()
开发者ID:s0undt3ch,项目名称:Deluge,代码行数:82,代码来源:core.py

示例8: WebApi

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class WebApi(JSONComponent):
    """
    The component that implements all the methods required for managing
    the web interface. The complete web json interface also exposes all the
    methods available from the core RPC.
    """

    def __init__(self):
        super(WebApi, self).__init__("Web", depend=["SessionProxy"])
        self.host_list = ConfigManager("hostlist.conf.1.2", DEFAULT_HOSTS)
        if not os.path.isfile(self.host_list.config_file):
            self.host_list.save()
        self.core_config = CoreConfig()
        self.event_queue = EventQueue()
        try:
            self.sessionproxy = component.get("SessionProxy")
        except KeyError:
            self.sessionproxy = SessionProxy()

    def get_host(self, host_id):
        """
        Return the information about a host

        :param host_id: the id of the host
        :type host_id: string
        :returns: the host information
        :rtype: list
        """
        for host in self.host_list["hosts"]:
            if host[0] == host_id:
                return host

    def start(self):
        self.core_config.start()
        self.sessionproxy.start()

    def stop(self):
        self.core_config.stop()
        self.sessionproxy.stop()

    @export
    def connect(self, host_id):
        """
        Connect the client to a daemon

        :param host_id: the id of the daemon in the host list
        :type host_id: string
        :returns: the methods the daemon supports
        :rtype: list
        """
        d = Deferred()
        def on_connected(methods):
            d.callback(methods)
        host = self.get_host(host_id)
        if host:
            self._json.connect(*host[1:]).addCallback(on_connected)
        return d

    @export
    def connected(self):
        """
        The current connection state.

        :returns: True if the client is connected
        :rtype: booleon
        """
        return client.connected()

    @export
    def disconnect(self):
        """
        Disconnect the web interface from the connected daemon.
        """
        client.disconnect()
        return True

    @export
    def update_ui(self, keys, filter_dict):
        """
        Gather the information required for updating the web interface.

        :param keys: the information about the torrents to gather
        :type keys: list
        :param filter_dict: the filters to apply when selecting torrents.
        :type filter_dict: dictionary
        :returns: The torrent and ui information.
        :rtype: dictionary
        """
        d = Deferred()
        ui_info = {
            "connected": client.connected(),
            "torrents": None,
            "filters": None,
            "stats": {
                "max_download": self.core_config.get("max_download_speed"),
                "max_upload": self.core_config.get("max_upload_speed"),
                "max_num_connections": self.core_config.get("max_connections_global")
            }
        }

#.........这里部分代码省略.........
开发者ID:Kash-Krishna,项目名称:SharkByte,代码行数:103,代码来源:json_api.py

示例9: Core

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class Core(component.Component):
    def __init__(self, listen_interface=None, read_only_config_keys=None):
        log.debug('Core init...')
        component.Component.__init__(self, 'Core')

        deluge_version = deluge.common.get_version()
        split_version = deluge.common.VersionSplit(deluge_version).version
        while len(split_version) < 4:
            split_version.append(0)

        deluge_fingerprint = lt.generate_fingerprint('DE', *split_version)
        user_agent = 'Deluge/{} libtorrent/{}'.format(deluge_version, self.get_libtorrent_version())

        # Start the libtorrent session.
        log.debug('Starting session (fingerprint: %s, user_agent: %s)', deluge_fingerprint, user_agent)
        settings_pack = {'peer_fingerprint': deluge_fingerprint,
                         'user_agent': user_agent,
                         'ignore_resume_timestamps': True}
        self.session = lt.session(settings_pack, flags=0)

        # Load the settings, if available.
        self._load_session_state()

        # Enable libtorrent extensions
        # Allows peers to download the metadata from the swarm directly
        self.session.add_extension('ut_metadata')
        # Ban peers that sends bad data
        self.session.add_extension('smart_ban')

        # Create the components
        self.eventmanager = EventManager()
        self.preferencesmanager = PreferencesManager()
        self.alertmanager = AlertManager()
        self.pluginmanager = PluginManager(self)
        self.torrentmanager = TorrentManager()
        self.filtermanager = FilterManager(self)
        self.authmanager = AuthManager()

        # New release check information
        self.new_release = None

        # External IP Address from libtorrent
        self.external_ip = None
        self.eventmanager.register_event_handler('ExternalIPEvent', self._on_external_ip_event)

        # GeoIP instance with db loaded
        self.geoip_instance = None

        # These keys will be dropped from the set_config() RPC and are
        # configurable from the command-line.
        self.read_only_config_keys = read_only_config_keys
        log.debug('read_only_config_keys: %s', read_only_config_keys)

        # Get the core config
        self.config = ConfigManager('core.conf')
        self.config.save()

        # If there was an interface value from the command line, use it, but
        # store the one in the config so we can restore it on shutdown
        self.__old_interface = None
        if listen_interface:
            if deluge.common.is_ip(listen_interface):
                self.__old_interface = self.config['listen_interface']
                self.config['listen_interface'] = listen_interface
            else:
                log.error('Invalid listen interface (must be IP Address): %s', listen_interface)

        # New release check information
        self.__new_release = None

        # Session status timer
        self.session_status = {}
        self.session_status_timer_interval = 0.5
        self.session_status_timer = task.LoopingCall(self.session.post_session_stats)
        self.alertmanager.register_handler('session_stats_alert', self._on_alert_session_stats)
        self._session_rates = {(k_rate, k_bytes): 0 for k_rate, k_bytes in SESSION_RATES_MAPPING.items()}
        self.session_rates_timer_interval = 2
        self.session_rates_timer = task.LoopingCall(self._update_session_rates)

    def start(self):
        """Starts the core"""
        self.session_status_timer.start(self.session_status_timer_interval)
        self.session_rates_timer.start(self.session_rates_timer_interval, now=False)

    def stop(self):
        log.debug('Core stopping...')

        if self.session_status_timer.running:
            self.session_status_timer.stop()

        if self.session_rates_timer.running:
            self.session_rates_timer.stop()

        # Save the libtorrent session state
        self._save_session_state()

        # We stored a copy of the old interface value
        if self.__old_interface:
            self.config['listen_interface'] = self.__old_interface

#.........这里部分代码省略.........
开发者ID:deluge-torrent,项目名称:deluge,代码行数:103,代码来源:core.py

示例10: Core

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class Core(CorePluginBase):
    def enable(self):
        self.config = ConfigManager("execute.conf", DEFAULT_CONFIG)
        event_manager = component.get("EventManager")
        self.torrent_manager = component.get("TorrentManager")
        self.registered_events = {}
        self.preremoved_cache = {}

        # Go through the commands list and register event handlers
        for command in self.config["commands"]:
            event = command[EXECUTE_EVENT]
            if event in self.registered_events:
                continue

            def create_event_handler(event):
                def event_handler(torrent_id):
                    self.execute_commands(torrent_id, event)
                return event_handler
            event_handler = create_event_handler(event)
            event_manager.register_event_handler(EVENT_MAP[event], event_handler)
            if event == "removed":
                event_manager.register_event_handler("PreTorrentRemovedEvent", self.on_preremoved)
            self.registered_events[event] = event_handler

        log.debug("Execute core plugin enabled!")

    def on_preremoved(self, torrent_id):
        # Get and store the torrent info before it is removed
        torrent = component.get("TorrentManager").torrents[torrent_id]
        info = torrent.get_status(["name", "save_path"])
        self.preremoved_cache[torrent_id] = [utf8_encoded(torrent_id), utf8_encoded(info["name"]),
                                              utf8_encoded(info["save_path"])]

    def execute_commands(self, torrent_id, event):
        if event == "added" and not self.torrent_manager.session_started:
            return
        elif event == "removed":
            torrent_id, torrent_name, save_path = self.preremoved_cache.pop(torrent_id)
        else:
            torrent = component.get("TorrentManager").torrents[torrent_id]
            info = torrent.get_status(["name", "save_path"])
            # getProcessOutputAndValue requires args to be str
            torrent_id = utf8_encoded(torrent_id)
            torrent_name = utf8_encoded(info["name"])
            save_path = utf8_encoded(info["save_path"])

        log.debug("[execute] Running commands for %s", event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn("[execute] command '%s' failed with exit code %d", command, exit_code)
                if stdout:
                    log.warn("[execute] stdout: %s", stdout)
                if stderr:
                    log.warn("[execute] stderr: %s", stderr)

        # Go through and execute all the commands
        for command in self.config["commands"]:
            if command[EXECUTE_EVENT] == event:
                command = os.path.expandvars(command[EXECUTE_COMMAND])
                command = os.path.expanduser(command)
                if os.path.isfile(command) and os.access(command, os.X_OK):
                    log.debug("[execute] Running %s", command)
                    d = getProcessOutputAndValue(command, (torrent_id, torrent_name, save_path), env=os.environ)
                    d.addCallback(log_error, command)
                else:
                    log.error("[execute] Execute script not found or not executable")

    def disable(self):
        self.config.save()
        event_manager = component.get("EventManager")
        for event, handler in self.registered_events.iteritems():
            event_manager.deregister_event_handler(event, handler)
        log.debug("Execute core plugin disabled!")

    ### Exported RPC methods ###
    @export
    def add_command(self, event, command):
        command_id = hashlib.sha1(str(time.time())).hexdigest()
        self.config["commands"].append((command_id, event, command))
        self.config.save()
        component.get("EventManager").emit(ExecuteCommandAddedEvent(command_id, event, command))

    @export
    def get_commands(self):
        return self.config["commands"]

    @export
    def remove_command(self, command_id):
        for command in self.config["commands"]:
            if command[EXECUTE_ID] == command_id:
                self.config["commands"].remove(command)
                component.get("EventManager").emit(ExecuteCommandRemovedEvent(command_id))
                break
        self.config.save()

    @export
    def save_command(self, command_id, event, cmd):
        for i, command in enumerate(self.config["commands"]):
#.........这里部分代码省略.........
开发者ID:EiNSTeiN-,项目名称:deluge-gtk3,代码行数:103,代码来源:core.py

示例11: AllTorrents

# 需要导入模块: from deluge.configmanager import ConfigManager [as 别名]
# 或者: from deluge.configmanager.ConfigManager import save [as 别名]
class AllTorrents(BaseMode, component.Component):
    def __init__(self, stdscr, encoding=None):
        self.torrent_names = None
        self.numtorrents = -1
        self._cached_rows = {}
        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.search_state = SEARCH_EMPTY

        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.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"]

        self.legacy_mode = Legacy(self.stdscr, self.encoding)

        if self.config["first_run"]:
            self.popup = Popup(self,"Welcome to Deluge" ,init_lines=self.__help_lines, height_req=0.75, width_req=65)
            self.config["first_run"] = False
            self.config.save()

    # component start/update
    def start(self):
        component.get("SessionProxy").get_torrents_status(self.__status_dict, self.__status_fields).addCallback(self.set_state,False)

    def update(self):
        component.get("SessionProxy").get_torrents_status(self.__status_dict, self.__status_fields).addCallback(self.set_state,True)
        if self.__torrent_info_id:
            component.get("SessionProxy").get_torrent_status(self.__torrent_info_id, self.__status_keys).addCallback(self._on_torrent_status)

    def update_config(self):
        self.config = ConfigManager("console.conf",DEFAULT_PREFS)
        s_primary = self.config["sort_primary"]
        s_secondary = self.config["sort_secondary"]
        self.__cols_to_show = [
            pref for pref in column_pref_names
                if ("show_%s" % pref) not in self.config
                or self.config["show_%s"%pref]
        ]

        self.__columns = [prefs_to_names[col] for col in self.__cols_to_show]
        self.__status_fields = column.get_required_fields(self.__columns)

        # we always need these, even if we're not displaying them
        for rf in ["state", "name", "queue", "progress"]:
            if rf not in self.__status_fields:
                self.__status_fields.append(rf)

        # same with sort keys
        if s_primary and (s_primary not in self.__status_fields):
            self.__status_fields.append(s_primary)
        if s_secondary and (s_secondary not in self.__status_fields):
#.........这里部分代码省略.........
开发者ID:Ashod,项目名称:Deluge,代码行数:103,代码来源:alltorrents.py


注:本文中的deluge.configmanager.ConfigManager.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。