Changeset 3742

Show
Ignore:
Timestamp:
08/24/08 04:36:10 (5 months ago)
Author:
andar
Message:

Add 'PreferencesManager?' component.
Clean up core.py a bit.
Fix DHT state saving/loading

Location:
trunk/deluge/core
Files:
1 added
1 modified

Legend:

Unmodified
Added
Removed
  • trunk/deluge/core/core.py

    r3728 r3742  
    5656from deluge.core.signalmanager import SignalManager 
    5757from deluge.core.filtermanager import FilterManager 
     58from deluge.core.preferencesmanager import PreferencesManager 
    5859from deluge.core.autoadd import AutoAdd 
    5960from deluge.log import LOG as log 
    60  
    61 DEFAULT_PREFS = { 
    62     "config_location": deluge.configmanager.get_config_dir(), 
    63     "send_info": False, 
    64     "info_sent": 0.0, 
    65     "daemon_port": 58846, 
    66     "allow_remote": False, 
    67     "compact_allocation": False, 
    68     "download_location": deluge.common.get_default_download_dir(), 
    69     "listen_ports": [6881, 6891], 
    70     "copy_torrent_file": False, 
    71     "torrentfiles_location": os.path.join(deluge.common.get_default_download_dir(), "torrentfiles"), 
    72     "plugins_location": os.path.join(deluge.configmanager.get_config_dir(), "plugins"), 
    73     "state_location": os.path.join(deluge.configmanager.get_config_dir(), "state"), 
    74     "prioritize_first_last_pieces": False, 
    75     "random_port": True, 
    76     "dht": True, 
    77     "upnp": True, 
    78     "natpmp": True, 
    79     "utpex": True, 
    80     "lsd": True, 
    81     "enc_in_policy": 1, 
    82     "enc_out_policy": 1, 
    83     "enc_level": 2, 
    84     "enc_prefer_rc4": True, 
    85     "max_connections_global": -1, 
    86     "max_upload_speed": -1.0, 
    87     "max_download_speed": -1.0, 
    88     "max_upload_slots_global": -1, 
    89     "max_half_open_connections": -1, 
    90     "max_connections_per_second": -1, 
    91     "ignore_limits_on_local_network": True, 
    92     "max_connections_per_torrent": -1, 
    93     "max_upload_slots_per_torrent": -1, 
    94     "max_upload_speed_per_torrent": -1, 
    95     "max_download_speed_per_torrent": -1, 
    96     "enabled_plugins": [], 
    97     "autoadd_location": deluge.common.get_default_download_dir(), 
    98     "autoadd_enable": False, 
    99     "add_paused": False, 
    100     "max_active_seeding": 5, 
    101     "max_active_downloading": 3, 
    102     "max_active_limit": 8, 
    103     "dont_count_slow_torrents": False, 
    104     "queue_new_to_top": False, 
    105     "stop_seed_at_ratio": False, 
    106     "remove_seed_at_ratio": False, 
    107     "stop_seed_ratio": 2.00, 
    108     "share_ratio_limit": 2.00, 
    109     "seed_time_ratio_limit": 7.00, 
    110     "seed_time_limit": 180, 
    111     "auto_managed": True, 
    112     "move_completed": False, 
    113     "move_completed_path": deluge.common.get_default_download_dir(), 
    114     "new_release_check": True, 
    115     "proxy_type" : 0, 
    116     "proxy_server" : "", 
    117     "proxy_username" : "", 
    118     "proxy_password" : "", 
    119     "proxy_port": 8080, 
    120     "outgoing_ports": [0, 0], 
    121     "random_outgoing_ports": True, 
    122     "peer_tos": "0x00", 
    123 } 
    12461 
    12562STATUS_KEYS = ['active_time', 'compact', 'distributed_copies', 'download_payload_rate', 'eta', 
     
    14279        self.client_address = None 
    14380 
     81        self.prefmanager = PreferencesManager() 
     82         
    14483        # Get config 
    145         self.config = deluge.configmanager.ConfigManager("core.conf", DEFAULT_PREFS) 
     84        self.config = deluge.configmanager.ConfigManager("core.conf") 
    14685 
    14786        if port == None: 
     
    241180        self.session.add_extension(lt.create_metadata_plugin) 
    242181 
    243         # Register set functions in the Config 
    244         self.config.register_set_function("torrentfiles_location", 
    245             self._on_set_torrentfiles_location) 
    246         self.config.register_set_function("state_location", 
    247             self._on_set_state_location) 
    248         self.config.register_set_function("listen_ports", 
    249             self._on_set_listen_ports) 
    250         self.config.register_set_function("random_port", 
    251             self._on_set_random_port) 
    252         self.config.register_set_function("outgoing_ports", 
    253             self._on_set_outgoing_ports) 
    254         self.config.register_set_function("random_outgoing_ports", 
    255             self._on_set_random_outgoing_ports) 
    256         self.config.register_set_function("peer_tos", 
    257             self._on_set_peer_tos) 
    258         self.config.register_set_function("dht", self._on_set_dht) 
    259         self.config.register_set_function("upnp", self._on_set_upnp) 
    260         self.config.register_set_function("natpmp", self._on_set_natpmp) 
    261         self.config.register_set_function("utpex", self._on_set_utpex) 
    262         self.config.register_set_function("lsd", self._on_set_lsd) 
    263         self.config.register_set_function("enc_in_policy", 
    264             self._on_set_encryption) 
    265         self.config.register_set_function("enc_out_policy", 
    266             self._on_set_encryption) 
    267         self.config.register_set_function("enc_level", 
    268             self._on_set_encryption) 
    269         self.config.register_set_function("enc_prefer_rc4", 
    270             self._on_set_encryption) 
    271         self.config.register_set_function("max_connections_global", 
    272             self._on_set_max_connections_global) 
    273         self.config.register_set_function("max_upload_speed", 
    274             self._on_set_max_upload_speed) 
    275         self.config.register_set_function("max_download_speed", 
    276             self._on_set_max_download_speed) 
    277         self.config.register_set_function("max_upload_slots_global", 
    278             self._on_set_max_upload_slots_global) 
    279         self.config.register_set_function("max_half_open_connections", 
    280             self._on_set_max_half_open_connections) 
    281         self.config.register_set_function("max_connections_per_second", 
    282             self._on_set_max_connections_per_second) 
    283         self.config.register_set_function("ignore_limits_on_local_network", 
    284             self._on_ignore_limits_on_local_network) 
    285         self.config.register_set_function("share_ratio_limit", 
    286             self._on_set_share_ratio_limit) 
    287         self.config.register_set_function("seed_time_ratio_limit", 
    288             self._on_set_seed_time_ratio_limit) 
    289         self.config.register_set_function("seed_time_limit", 
    290             self._on_set_seed_time_limit) 
    291         self.config.register_set_function("max_active_downloading", 
    292             self._on_set_max_active_downloading) 
    293         self.config.register_set_function("max_active_seeding", 
    294             self._on_set_max_active_seeding) 
    295         self.config.register_set_function("max_active_limit", 
    296             self._on_set_max_active_limit) 
    297         self.config.register_set_function("dont_count_slow_torrents", 
    298             self._on_set_dont_count_slow_torrents) 
    299         self.config.register_set_function("send_info", 
    300             self._on_send_info) 
    301         self.config.register_set_function("proxy_type", 
    302             self._on_set_proxy) 
    303         self.config.register_set_function("proxy_username", 
    304             self._on_set_proxy) 
    305         self.config.register_set_function("proxy_password", 
    306             self._on_set_proxy) 
    307         self.config.register_set_function("proxy_server", 
    308             self._on_set_proxy) 
    309         self.config.register_set_function("proxy_port", 
    310             self._on_set_proxy) 
    311         self.new_release = None 
    312         self.new_release_timer = None 
    313         self.config.register_set_function("new_release_check", 
    314             self._on_new_release_check) 
    315  
    316         self.config.register_change_callback(self._on_config_value_change) 
    317182        # Start the AlertManager 
    318183        self.alerts = AlertManager(self.session) 
     
    333198        self.autoadd = AutoAdd() 
    334199 
     200        # New release check information 
     201        self.new_release = None 
     202         
    335203        component.start() 
    336204 
     
    361229        log.info("Shutting down core..") 
    362230        self._should_shutdown = True 
    363         # Shutdown dht 
    364         self._on_set_dht(False, False) 
     231 
     232        # Save the DHT state if necessary 
     233        if self.config["dht"]: 
     234            self.save_dht_state() 
     235             
    365236        # Shutdown the socket 
    366237        try: 
     
    386257            pass 
    387258 
    388     # Exported Methods 
    389     def export_ping(self): 
    390         """A method to see if the core is running""" 
    391         return True 
    392  
    393     def export_shutdown(self): 
    394         """Shutdown the core""" 
    395         # Make shutdown an async call 
    396         gobject.idle_add(self._shutdown) 
    397  
    398     def export_register_client(self, port): 
    399         """Registers a client with the signal manager so that signals are 
    400             sent to it.""" 
    401         self.signals.register_client(self.client_address, port) 
    402         if self.config["new_release_check"]: 
    403             self.check_new_release() 
    404  
    405     def export_deregister_client(self): 
    406         """De-registers a client with the signal manager.""" 
    407         self.signals.deregister_client(self.client_address) 
    408  
    409     def export_add_torrent_file(self, filename, filedump, options): 
    410         """Adds a torrent file to the libtorrent session 
    411             This requires the torrents filename and a dump of it's content 
    412         """ 
    413         gobject.idle_add(self._add_torrent_file, filename, filedump, options) 
    414  
    415     def _add_torrent_file(self, filename, filedump, options): 
    416         # Turn the filedump into a torrent_info 
    417         if not isinstance(filedump, str): 
    418             filedump = filedump.data 
    419  
    420         if len(filedump) == 0: 
    421             log.warning("Torrent file is corrupt!") 
    422             return 
    423  
    424         try: 
    425             torrent_info = lt.torrent_info(lt.bdecode(filedump)) 
    426         except RuntimeError, e: 
    427             log.warning("Unable to decode torrent file: %s", e) 
    428             return None 
    429  
    430         torrent_id = self.torrents.add(filedump=filedump, options=options, filename=filename) 
    431  
    432         # Run the plugin hooks for 'post_torrent_add' 
    433         self.plugins.run_post_torrent_add(torrent_id) 
    434  
    435     def export_add_torrent_url(self, url, save_path, options): 
    436         log.info("Attempting to add url %s", url) 
    437  
    438         # Get the actual filename of the torrent from the url provided. 
    439         filename = url.split("/")[-1] 
    440  
    441         # Get the .torrent file from the url 
    442         torrent_file = deluge.common.fetch_url(url) 
    443         if torrent_file is None: 
    444             return False 
    445  
    446         # Dump the torrents file contents to a string 
    447         try: 
    448             filedump = open(torrent_file, "rb").read() 
    449         except IOError: 
    450             log.warning("Unable to open %s for reading.", torrent_file) 
    451             return False 
    452  
    453         # Add the torrent to session 
    454         return self.export_add_torrent_file( 
    455             filename, filedump, options) 
    456  
    457     def export_remove_torrent(self, torrent_ids, remove_torrent, remove_data): 
    458         log.debug("Removing torrent %s from the core.", torrent_ids) 
    459         for torrent_id in torrent_ids: 
    460             if self.torrents.remove(torrent_id, remove_torrent, remove_data): 
    461                 # Run the plugin hooks for 'post_torrent_remove' 
    462                 self.plugins.run_post_torrent_remove(torrent_id) 
    463  
    464     def export_force_reannounce(self, torrent_ids): 
    465         log.debug("Forcing reannouncment to: %s", torrent_ids) 
    466         for torrent_id in torrent_ids: 
    467             self.torrents[torrent_id].force_reannounce() 
    468  
    469     def export_pause_torrent(self, torrent_ids): 
    470         log.debug("Pausing: %s", torrent_ids) 
    471         for torrent_id in torrent_ids: 
    472             if not self.torrents[torrent_id].pause(): 
    473                 log.warning("Error pausing torrent %s", torrent_id) 
    474  
    475     def export_move_storage(self, torrent_ids, dest): 
    476         log.debug("Moving storage %s to %s", torrent_ids, dest) 
    477         for torrent_id in torrent_ids: 
    478             if not self.torrents[torrent_id].move_storage(dest): 
    479                 log.warning("Error moving torrent %s to %s", torrent_id, dest) 
    480  
    481     def export_pause_all_torrents(self): 
    482         """Pause all torrents in the session""" 
    483         self.session.pause() 
    484  
    485     def export_resume_all_torrents(self): 
    486         """Resume all torrents in the session""" 
    487         self.session.resume() 
    488         self.torrent_all_resumed() 
    489  
    490     def export_resume_torrent(self, torrent_ids): 
    491         log.debug("Resuming: %s", torrent_ids) 
    492         for torrent_id in torrent_ids: 
    493             if self.torrents[torrent_id].resume(): 
    494                 self.torrent_resumed(torrent_id) 
    495  
    496     def export_get_status_keys(self): 
    497         """ 
    498         returns all possible keys for the keys argument in get_torrent(s)_status. 
    499         """ 
    500         return STATUS_KEYS + self.plugins.status_fields.keys() 
    501  
    502     def export_get_torrent_status(self, torrent_id, keys): 
    503         # Build the status dictionary 
    504         try: 
    505             status = self.torrents[torrent_id].get_status(keys) 
    506         except KeyError: 
    507             # The torrent_id is not found in the torrentmanager, so return None 
    508             return None 
    509  
    510         # Get the leftover fields and ask the plugin manager to fill them 
    511         leftover_fields = list(set(keys) - set(status.keys())) 
    512         if len(leftover_fields) > 0: 
    513             status.update(self.plugins.get_status(torrent_id, leftover_fields)) 
    514         return status 
    515  
    516     def export_get_torrents_status(self, filter_dict, keys ): 
    517         """ 
    518         returns all torrents , optionally filtered by filter_dict. 
    519         """ 
    520         torrent_ids = self.filtermanager.filter_torrent_ids(filter_dict) 
    521         status_dict = {}.fromkeys(torrent_ids) 
    522  
    523         # Get the torrent status for each torrent_id 
    524         for torrent_id in torrent_ids: 
    525             status_dict[torrent_id] = self.export_get_torrent_status(torrent_id, keys) 
    526         # Emit the torrent_status signal to the clients 
    527         return status_dict 
    528  
    529     def export_get_filter_tree(self): 
    530         """ 
    531         returns {field: [(value,count)] } 
    532         for use in sidebar(s) 
    533         """ 
    534         return self.filtermanager.get_filter_tree() 
    535  
    536     def export_get_session_state(self): 
    537         """Returns a list of torrent_ids in the session.""" 
    538         # Get the torrent list from the TorrentManager 
    539         return self.torrents.get_torrent_list() 
    540  
    541     def export_save_state(self): 
    542         """Save the current session state to file.""" 
    543         # Have the TorrentManager save it's state 
    544         self.torrents.save_state() 
    545  
    546     def export_get_config(self): 
    547         """Get all the preferences as a dictionary""" 
    548         return self.config.get_config() 
    549  
    550     def export_get_config_value(self, key): 
    551         """Get the config value for key""" 
    552         try: 
    553             value = self.config[key] 
    554         except KeyError: 
    555             return None 
    556  
    557         return value 
    558  
    559     def export_set_config(self, config): 
    560         """Set the config with values from dictionary""" 
    561         config = deluge.common.pythonize(config) 
    562         # Load all the values into the configuration 
    563         for key in config.keys(): 
    564             self.config[key] = config[key] 
    565  
    566     def export_get_listen_port(self): 
    567         """Returns the active listen port""" 
    568         return self.session.listen_port() 
    569  
    570     def export_get_num_connections(self): 
    571         """Returns the current number of connections""" 
    572         return self.session.num_connections() 
    573  
    574     def export_get_dht_nodes(self): 
    575         """Returns the number of dht nodes""" 
    576         return self.session.status().dht_nodes 
    577  
    578     def export_get_download_rate(self): 
    579         """Returns the payload download rate""" 
    580         return self.session.status().payload_download_rate 
    581  
    582     def export_get_upload_rate(self): 
    583         """Returns the payload upload rate""" 
    584         return self.session.status().payload_upload_rate 
    585  
    586     def export_get_available_plugins(self): 
    587         """Returns a list of plugins available in the core""" 
    588         return self.plugins.get_available_plugins() 
    589  
    590     def export_get_enabled_plugins(self): 
    591         """Returns a list of enabled plugins in the core""" 
    592         return self.plugins.get_enabled_plugins() 
    593  
    594     def export_enable_plugin(self, plugin): 
    595         self.plugins.enable_plugin(plugin) 
    596         return None 
    597  
    598     def export_disable_plugin(self, plugin): 
    599         self.plugins.disable_plugin(plugin) 
    600         return None 
    601  
    602     def export_force_recheck(self, torrent_ids): 
    603         """Forces a data recheck on torrent_ids""" 
    604         for torrent_id in torrent_ids: 
    605             self.torrents[torrent_id].force_recheck() 
    606  
    607     def export_set_torrent_trackers(self, torrent_id, trackers): 
    608         """Sets a torrents tracker list.  trackers will be [{"url", "tier"}]""" 
    609         return self.torrents[torrent_id].set_trackers(trackers) 
    610  
    611     def export_set_torrent_max_connections(self, torrent_id, value): 
    612         """Sets a torrents max number of connections""" 
    613         return self.torrents[torrent_id].set_max_connections(value) 
    614  
    615     def export_set_torrent_max_upload_slots(self, torrent_id, value): 
    616         """Sets a torrents max number of upload slots""" 
    617         return self.torrents[torrent_id].set_max_upload_slots(value) 
    618  
    619     def export_set_torrent_max_upload_speed(self, torrent_id, value): 
    620         """Sets a torrents max upload speed""" 
    621         return self.torrents[torrent_id].set_max_upload_speed(value) 
    622  
    623     def export_set_torrent_max_download_speed(self, torrent_id, value): 
    624         """Sets a torrents max download speed""" 
    625         return self.torrents[torrent_id].set_max_download_speed(value) 
    626  
    627     def export_set_torrent_file_priorities(self, torrent_id, priorities): 
    628         """Sets a torrents file priorities""" 
    629         return self.torrents[torrent_id].set_file_priorities(priorities) 
    630  
    631     def export_set_torrent_prioritize_first_last(self, torrent_id, value): 
    632         """Sets a higher priority to the first and last pieces""" 
    633         return self.torrents[torrent_id].set_prioritize_first_last(value) 
    634  
    635     def export_set_torrent_auto_managed(self, torrent_id, value): 
    636         """Sets the auto managed flag for queueing purposes""" 
    637         return self.torrents[torrent_id].set_auto_managed(value) 
    638  
    639     def export_set_torrent_stop_at_ratio(self, torrent_id, value): 
    640         """Sets the torrent to stop at 'stop_ratio'""" 
    641         return self.torrents[torrent_id].set_stop_at_ratio(value) 
    642  
    643     def export_set_torrent_stop_ratio(self, torrent_id, value): 
    644         """Sets the ratio when to stop a torrent if 'stop_at_ratio' is set""" 
    645         return self.torrents[torrent_id].set_stop_ratio(value) 
    646  
    647     def export_set_torrent_remove_at_ratio(self, torrent_id, value): 
    648         """Sets the torrent to be removed at 'stop_ratio'""" 
    649         return self.torrents[torrent_id].set_remove_at_ratio(value) 
    650  
    651     def export_set_torrent_move_on_completed(self, torrent_id, value): 
    652         """Sets the torrent to be moved when completed""" 
    653         return self.torrents[torrent_id].set_move_on_completed(value) 
    654  
    655     def export_set_torrent_move_on_completed_path(self, torrent_id, value): 
    656         """Sets the path for the torrent to be moved when completed""" 
    657         return self.torrents[torrent_id].set_move_on_completed_path(value) 
    658  
    659     def export_block_ip_range(self, range): 
    660         """Block an ip range""" 
    661         try: 
    662             self.ip_filter.add_rule(range[0], range[1], 1) 
    663         except AttributeError: 
    664             self.export_reset_ip_filter() 
    665             self.ip_filter.add_rule(range[0], range[1], 1) 
    666  
    667     def export_reset_ip_filter(self): 
    668         """Clears the ip filter""" 
    669         self.ip_filter = lt.ip_filter() 
    670         self.session.set_ip_filter(self.ip_filter) 
    671  
    672     def export_get_health(self): 
    673         """Returns True if we have established incoming connections""" 
    674         return self.session.status().has_incoming_connections 
    675  
    676     ## Queueing functions ## 
    677     def export_queue_top(self, torrent_ids): 
    678         log.debug("Attempting to queue %s to top", torrent_ids) 
    679         for torrent_id in torrent_ids: 
    680             try: 
    681                 # If the queue method returns True, then we should emit a signal 
    682                 if self.torrents.queue_top(torrent_id): 
    683                     self._torrent_queue_changed() 
    684             except KeyError: 
    685                 log.warning("torrent_id: %s does not exist in the queue", torrent_id) 
    686  
    687     def export_queue_up(self, torrent_ids): 
    688         log.debug("Attempting to queue %s to up", torrent_ids) 
    689         #torrent_ids must be sorted before moving. 
    690         torrent_ids.sort(key = lambda id: self.torrents.torrents[id].get_queue_position()) 
    691         for torrent_id in torrent_ids: 
    692             try: 
    693                 # If the queue method returns True, then we should emit a signal 
    694                 if self.torrents.queue_up(torrent_id): 
    695                     self._torrent_queue_changed() 
    696             except KeyError: 
    697                 log.warning("torrent_id: %s does not exist in the queue", torrent_id) 
    698  
    699     def export_queue_down(self, torrent_ids): 
    700         log.debug("Attempting to queue %s to down", torrent_ids) 
    701         #torrent_ids must be sorted before moving. 
    702         torrent_ids.sort(key = lambda id: -self.torrents.torrents[id].get_queue_position()) 
    703         for torrent_id in torrent_ids: 
    704             try: 
    705                 # If the queue method returns True, then we should emit a signal 
    706                 if self.torrents.queue_down(torrent_id): 
    707                     self._torrent_queue_changed() 
    708             except KeyError: 
    709                 log.warning("torrent_id: %s does not exist in the queue", torrent_id) 
    710  
    711     def export_queue_bottom(self, torrent_ids): 
    712         log.debug("Attempting to queue %s to bottom", torrent_ids) 
    713         for torrent_id in torrent_ids: 
    714             try: 
    715                 # If the queue method returns True, then we should emit a signal 
    716                 if self.torrents.queue_bottom(torrent_id): 
    717                     self._torrent_queue_changed() 
    718             except KeyError: 
    719                 log.warning("torrent_id: %s does not exist in the queue", torrent_id) 
    720  
    721     # Signals 
    722     def torrent_removed(self, torrent_id): 
    723         """Emitted when a torrent has been removed from the core""" 
    724         log.debug("torrent_remove signal emitted") 
    725         self.signals.emit("torrent_removed", torrent_id) 
    726  
    727     def torrent_paused(self, torrent_id): 
    728         """Emitted when a torrent is paused""" 
    729         log.debug("torrent_paused signal emitted") 
    730         self.signals.emit("torrent_paused", torrent_id) 
    731  
    732     def torrent_resumed(self, torrent_id): 
    733         """Emitted when a torrent is resumed""" 
    734         log.debug("torrent_resumed signal emitted") 
    735         self.signals.emit("torrent_resumed", torrent_id) 
    736  
    737     def torrent_all_paused(self): 
    738         """Emitted when all torrents have been paused""" 
    739         log.debug("torrent_all_paused signal emitted") 
    740         self.signals.emit("torrent_all_paused") 
    741  
    742     def torrent_all_resumed(self): 
    743         """Emitted when all torrents have been resumed""" 
    744         log.debug("torrent_all_resumed signal emitted") 
    745         self.signals.emit("torrent_all_resumed") 
    746  
    747     def config_value_changed(self, key, value): 
    748         """Emitted when a config value has changed""" 
    749         log.debug("config_value_changed signal emitted") 
    750         self.signals.emit("config_value_changed", key, value) 
    751  
    752     def _torrent_queue_changed(self): 
    753         """Emitted when a torrent queue position is changed""" 
    754         log.debug("torrent_queue_changed signal emitted") 
    755         self.signals.emit("torrent_queue_changed") 
    756  
    757     # Config set functions 
    758     def _on_config_value_change(self, key, value): 
    759         self.config_value_changed(key, value) 
    760  
    761     def _on_set_torrentfiles_location(self, key, value): 
    762         if self.config["copy_torrent_file"]: 
    763             try: 
    764                 os.makedirs(value) 
    765             except Exception, e: 
    766                 log.debug("Unable to make directory: %s", e) 
    767  
    768     def _on_set_state_location(self, key, value): 
    769         if not os.access(value, os.F_OK): 
    770             try: 
    771                 os.makedirs(value) 
    772             except Exception, e: 
    773                 log.debug("Unable to make directory: %s", e) 
    774  
    775     def _on_set_listen_ports(self, key, value): 
    776         # Only set the listen ports if random_port is not true 
    777         if self.config["random_port"] is not True: 
    778             log.debug("listen port range set to %s-%s", value[0], value[1]) 
    779             self.session.listen_on(value[0], value[1]) 
    780  
    781     def _on_set_random_port(self, key, value): 
    782         log.debug("random port value set to %s", value) 
    783         # We need to check if the value has been changed to true and false 
    784         # and then handle accordingly. 
    785         if value: 
    786             import random 
    787             listen_ports = [] 
    788             randrange = lambda: random.randrange(49152, 65525) 
    789             listen_ports.append(randrange()) 
    790             listen_ports.append(listen_ports[0]+10) 
    791         else: 
    792             listen_ports = self.config["listen_ports"] 
    793  
    794         # Set the listen ports 
    795         log.debug("listen port range set to %s-%s", listen_ports[0], 
    796             listen_ports[1]) 
    797         self.session.listen_on(listen_ports[0], listen_ports[1]) 
    798  
    799     def _on_set_outgoing_ports(self, key, value): 
    800         if not self.config["random_outgoing_ports"]: 
    801             log.debug("outgoing port range set to %s-%s", value[0], value[1]) 
    802             self.session.outgoing_ports(value[0], value[1]) 
    803  
    804     def _on_set_random_outgoing_ports(self, key, value): 
    805         if value: 
    806             self.session.outgoing_ports(0, 0) 
    807  
    808     def _on_set_peer_tos(self, key, value): 
    809         log.debug("setting peer_tos to: %s", value) 
    810         try: 
    811             self.settings.peer_tos = str(int(value, 16)) 
    812         except ValueError, e: 
    813             log.debug("Invalid tos byte: %s", e) 
    814             return 
    815  
    816         self.session.set_settings(self.settings) 
    817  
    818     def _on_set_dht(self, key, value): 
    819         log.debug("dht value set to %s", value) 
    820         state_file = deluge.common.get_default_config_dir('dht.state') 
    821         if value: 
    822             if os.path.exists(state_file): 
    823                 try: 
    824                     dht_data = open(state_file, 'rb') 
    825                     state_contents = dht_data.readlines() 
    826                     dht_data.close() 
    827                 except IOError: 
    828                     log.warning("failed to read dht state file") 
    829             else: 
    830                 state_contents = None 
    831             try: 
    832                 self.session.start_dht(state_contents) 
    833             except: 
    834                 log.warning("restoring old dht state failed") 
    835                 self.session.start_dht(None) 
    836             self.session.add_dht_router("router.bittorrent.com", 6881) 
    837             self.session.add_dht_router("router.utorrent.com", 6881) 
    838             self.session.add_dht_router("router.bitcomet.com", 6881) 
    839         else: 
    840             try: 
    841                 dht_data = open(state_file, 'wb') 
    842                 dht_data.writelines('%s' % (self.session.dht_state())) 
    843                 dht_data.close() 
    844             except IOError: 
    845                 log.warning("failed to save dht state to file") 
    846             self.session.stop_dht() 
    847  
    848     def _on_set_upnp(self, key, value): 
    849         log.debug("upnp value set to %s", value) 
    850         if value: 
    851             self.session.start_upnp() 
    852         else: 
    853             self.session.stop_upnp() 
    854  
    855     def _on_set_natpmp(self, key, value): 
    856         log.debug("natpmp value set to %s", value) 
    857         if value: 
    858             self.session.start_natpmp() 
    859         else: 
    860             self.session.stop_natpmp() 
    861  
    862     def _on_set_lsd(self, key, value): 
    863         log.debug("lsd value set to %s", value) 
    864         if value: 
    865             self.session.start_lsd() 
    866         else: 
    867             self.session.stop_lsd() 
    868  
    869     def _on_set_utpex(self, key, value): 
    870         log.debug("utpex value set to %s", value) 
    871         if value: 
    872             self.session.add_extension(lt.create_ut_pex_plugin) 
    873  
    874     def _on_set_encryption(self, key, value): 
    875         log.debug("encryption value %s set to %s..", key, value) 
    876         pe_settings = lt.pe_settings() 
    877         pe_settings.out_enc_policy = \ 
    878             lt.enc_policy(self.config["enc_out_policy"]) 
    879         pe_settings.in_enc_policy = lt.enc_policy(self.config["enc_in_policy"]) 
    880         pe_settings.allowed_enc_level = lt.enc_level(self.config["enc_level"]) 
    881         pe_settings.prefer_rc4 = self.config["enc_prefer_rc4"] 
    882         self.session.set_pe_settings(pe_settings) 
    883         set = self.session.get_pe_settings() 
    884         log.debug("encryption settings:\n\t\t\tout_policy: %s\n\t\t\ 
    885         in_policy: %s\n\t\t\tlevel: %s\n\t\t\tprefer_rc4: %s", 
    886             set.out_enc_policy, 
    887             set.in_enc_policy, 
    888             set.allowed_enc_level, 
    889             set.prefer_rc4) 
    890  
    891     def _on_set_max_connections_global(self, key, value): 
    892         log.debug("max_connections_global set to %s..", value) 
    893         self.session.set_max_connections(value) 
    894  
    895     def _on_set_max_upload_speed(self, key, value): 
    896         log.debug("max_upload_speed set to %s..", value) 
    897         # We need to convert Kb/s to B/s 
    898         if value < 0: 
    899             v = -1 
    900         else: 
    901             v = int(value * 1024) 
    902