def test_configparser_copy(self): ccp = CallbackConfigParser() ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) copy_ccp = ccp.copy() self.assertEqual(copy_ccp.get('general', 'version'), 11) self.assertTrue(copy_ccp.get('search_community', 'enabled'))
def load(filename=None): """ Load a saved SessionStartupConfig from disk. @param filename An absolute Unicode filename, if None, the default path will be used. @return SessionStartupConfig object """ if not filename: # Then try to read from default location filename = SessionStartupConfig.get_default_config_filename( SessionStartupConfig.get_default_state_dir()) if not os.path.isfile(filename): # No config on the default location, just start from scratch return SessionStartupConfig() # Class method, no locking required sessconfig = CallbackConfigParser() try: sessconfig.read_file(filename) except: # Config file seems to be corrupt, backup the file and start from scratch copyfile( filename, os.path.join(os.path.dirname(filename), 'corrupt_config.bak')) return SessionStartupConfig() return SessionStartupConfig(sessconfig)
def copy(self): config = CallbackConfigParser() config._sections = { 'downloadconfig': copy.deepcopy(self.dlconfig._sections['downloadconfig']) } return DownloadStartupConfig(config)
def test_configparser_copy(self): ccp = CallbackConfigParser() ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) copy_ccp = ccp.copy() self.assertEqual(copy_ccp.get('general', 'version'), 11) self.assertTrue(copy_ccp.get('search_community', 'enabled'))
def test_multifile_torrent(self): tdef = TorrentDef() tdef.add_content(os.path.join(TESTS_DATA_DIR, "video.avi")) tdef.set_tracker("http://tribler.org/announce") tdef.save() impl = LibtorrentDownloadImpl(self.session, tdef) # Override the add_torrent because it will be called impl.ltmgr = MockObject() impl.ltmgr.add_torrent = lambda _, _dummy2: succeed(fake_handler) impl.set_selected_files = lambda: None fake_handler = MockObject() fake_handler.is_valid = lambda: True fake_handler.status = lambda: fake_status fake_handler.set_share_mode = lambda _: None fake_handler.set_priority = lambda _: None fake_handler.set_sequential_download = lambda _: None fake_handler.resume = lambda: None fake_handler.set_max_connections = lambda _: None fake_status = MockObject() fake_status.share_mode = False # Create a dummy download config impl.dlconfig = DownloadStartupConfig().dlconfig.copy() # Create a dummy pstate pstate = CallbackConfigParser() pstate.add_section("state") test_dict = dict() test_dict["a"] = "b" pstate.set("state", "engineresumedata", test_dict) return impl.network_create_engine_wrapper(pstate)
def __init__(self, session): super(WatchFolder, self).__init__() self._logger = logging.getLogger(self.__class__.__name__) self.session = session gui_config_file_path = os.path.join(self.session.get_state_dir(), STATEDIR_GUICONFIG) config = CallbackConfigParser() config.read_file(gui_config_file_path, 'utf-8-sig') self.tribler_gui_config = config.get_config_as_json()
def __init__(self, session): resource.Resource.__init__(self) self.session = session # Load the Tribler GUI configuration file self.gui_config_file_path = os.path.join(self.session.get_state_dir(), STATEDIR_GUICONFIG) self.tribler_gui_config = CallbackConfigParser() self.tribler_gui_config.read_file(self.gui_config_file_path, 'utf-8-sig')
def resume_ready(_): """ check if resume data is ready """ basename = binascii.hexlify(tdef.get_infohash()) + '.state' filename = os.path.join(self.session.get_downloads_pstate_dir(), basename) engine_data = CallbackConfigParser() engine_data.read_file(filename) self.assertEqual(tdef.get_infohash(), engine_data.get('state', 'engineresumedata').get('info-hash'))
def load(filename): """ Load a saved DownloadStartupConfig from disk. @param filename An absolute Unicode filename @return DownloadStartupConfig object """ # Class method, no locking required dlconfig = CallbackConfigParser() try: dlconfig.read_file(filename) except: raise IOError, "Failed to open download config file" return DownloadStartupConfig(dlconfig)
def test_configparser_false_callback(self): def parser_callback(section, option, old_value, new_value): return False ccp = CallbackConfigParser() ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) ccp.set_callback(parser_callback) ccp.set('search_community', 'enabled', False)
def load(filename): """ Load a saved DownloadStartupConfig from disk. @param filename An absolute Unicode filename @return DownloadStartupConfig object """ # Class method, no locking required dlconfig = CallbackConfigParser() try: dlconfig.read_file(filename) except: raise IOError, "Failed to open download config file" return DownloadStartupConfig(dlconfig)
def load(filename): """ Load a saved DownloadStartupConfig from disk. @param filename An absolute Unicode filename @return DownloadStartupConfig object """ # Class method, no locking required dlconfig = CallbackConfigParser() try: dlconfig.read_file(filename) except (ParsingError, IOError, MissingSectionHeaderError): logger.error("Failed to open download config file: %s", filename) raise return DownloadStartupConfig(dlconfig)
def __init__(self, dlconfig=None): super(DownloadConfigInterface, self).__init__() self.dlconfig = dlconfig or CallbackConfigParser() # Dumb^WPoor man's versioning of DownloadConfig, add missing default values. write = False for section, sect_dict in dldefaults.iteritems(): if not self.dlconfig.has_section(section): self.dlconfig.add_section(section) for k, v in sect_dict.iteritems(): if not self.dlconfig.has_option(section, k): write = True self.dlconfig.set(section, k, v) if write and self.dlconfig.filename: self.dlconfig.write_file() if dlconfig: # TODO(emilon): I guess this can be removed? # modify/fix incorrectly saved dlconfigs if dlconfig.has_option('downloadconfig', 'saveas') and isinstance( dlconfig.get('downloadconfig', 'saveas'), tuple): dlconfig.set('downloadconfig', 'saveas', dlconfig.get('saveas')[-1])
def load(filename): """ Load a saved DownloadStartupConfig from disk. @param filename An absolute Unicode filename @return DownloadStartupConfig object """ # Class method, no locking required dlconfig = CallbackConfigParser() try: dlconfig.read_file(filename) except (ParsingError, IOError, MissingSectionHeaderError): logger.error("Failed to open download config file: %s", filename) raise return DownloadStartupConfig(dlconfig)
def test_configparser_config1(self): ccp = CallbackConfigParser() ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) self.assertEqual(ccp.get('general', 'version'), 11) self.assertTrue(ccp.get('search_community', 'enabled')) self.assertIsInstance( ccp.get('tunnel_community', 'socks5_listen_ports'), list) self.assertFalse(ccp.get('foo', 'bar'))
def test_configparser_false_callback(self): def parser_callback(section, option, old_value, new_value): return False ccp = CallbackConfigParser() ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) ccp.set_callback(parser_callback) ccp.set('search_community', 'enabled', False)
def test_configparser_config1(self): ccp = CallbackConfigParser() ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) self.assertEqual(ccp.get('general', 'version'), 11) self.assertTrue(ccp.get('search_community', 'enabled')) self.assertIsInstance(ccp.get('tunnel_community', 'socks5_listen_ports'), list) self.assertFalse(ccp.get('foo', 'bar'))
def test_configparser_write_file_defaults(self): ccp = CallbackConfigParser(defaults={'foo': 'bar'}) new_path = os.path.join(self.session_base_dir, 'config_new.conf') ccp.write_file(new_path) self.assertTrue(os.path.isfile(new_path)) ccp.read_file(new_path) self.assertEqual(ccp.get('DEFAULT', 'foo'), 'bar')
def setupConfig(self): self.configfilepath = os.path.join(self.getConfigPath(), STATEDIR_GUICONFIG) self.config = CallbackConfigParser() # Load the config file. if os.path.exists(self.configfilepath): self.config.read_file(self.configfilepath, 'utf-8-sig') if not self.config.has_section('Tribler'): self.config.add_section('Tribler') # Tribler.conf also contains the default download config. So we need to merge it now. if not self.config.has_section('downloadconfig'): self.config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance( ).dlconfig._sections['downloadconfig'].iteritems(): self.config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = self.config
def test_downloadconfig(self): dlconf = CallbackConfigParser() dlconf.add_section('downloadconfig') dlconf.set('downloadconfig', 'hops', 5) dlcfg = DownloadConfigInterface(dlconf) self.assertIsInstance(dlcfg.get_dest_dir(), unicode) dlcfg.set_dest_dir(self.session_base_dir) self.assertEqual(dlcfg.get_dest_dir(), self.session_base_dir) dlcfg.set_corrected_filename("foobar") self.assertEqual(dlcfg.get_corrected_filename(), "foobar") dlcfg.set_mode(1) self.assertEqual(dlcfg.get_mode(), 1) dlcfg.set_hops(4) self.assertEqual(dlcfg.get_hops(), 4) dlcfg.set_safe_seeding(False) self.assertFalse(dlcfg.get_safe_seeding()) dlcfg.set_selected_files("foo.bar") self.assertEqual(dlcfg.get_selected_files(), ["foo.bar"]) dlcfg.set_max_speed(UPLOAD, 1337) dlcfg.set_max_speed(DOWNLOAD, 1338) self.assertEqual(dlcfg.get_max_speed(UPLOAD), 1337) self.assertEqual(dlcfg.get_max_speed(DOWNLOAD), 1338)
def test_multifile_torrent(self): tdef = TorrentDef() dn = os.path.join(TESTS_DATA_DIR, "contentdir") tdef.add_content(dn, "dirintorrent") fn = os.path.join(TESTS_DATA_DIR, "video.avi") tdef.add_content(fn, os.path.join("dirintorrent", "video.avi")) tdef.set_tracker("http://tribler.org/announce") tdef.finalize() impl = LibtorrentDownloadImpl(self.session, tdef) # Override the add_torrent because it will be called impl.ltmgr = MockObject() impl.ltmgr.add_torrent = lambda _, _dummy2: fake_handler impl.set_selected_files = lambda: None fake_handler = MockObject() fake_handler.is_valid = lambda: True fake_handler.status = lambda: fake_status fake_handler.set_share_mode = lambda _: None fake_handler.resume = lambda: None fake_handler.resolve_countries = lambda _: None fake_status = MockObject() fake_status.share_mode = False # Create a dummy download config impl.dlconfig = DownloadStartupConfig().dlconfig.copy() # Create a dummy pstate pstate = CallbackConfigParser() pstate.add_section("state") test_dict = dict() test_dict["a"] = "b" pstate.set("state", "engineresumedata", test_dict) return impl.network_create_engine_wrapper(pstate)
def load(filename=None): """ Load a saved SessionStartupConfig from disk. @param filename An absolute Unicode filename, if None, the default path will be used. @return SessionStartupConfig object """ if not filename: # Then try to read from default location filename = SessionStartupConfig.get_default_config_filename(SessionStartupConfig.get_default_state_dir()) if not os.path.isfile(filename): # No config on the default location, just start from scratch return SessionStartupConfig() # Class method, no locking required sessconfig = CallbackConfigParser() try: sessconfig.read_file(filename) except: raise IOError("Failed to open session config file") return SessionStartupConfig(sessconfig)
def load(filename=None): """ Load a saved SessionStartupConfig from disk. @param filename An absolute Unicode filename, if None, the default path will be used. @return SessionStartupConfig object """ if not filename: # Then try to read from default location filename = SessionStartupConfig.get_default_config_filename( SessionStartupConfig.get_default_state_dir()) if not os.path.isfile(filename): # No config on the default location, just start from scratch return SessionStartupConfig() # Class method, no locking required sessconfig = CallbackConfigParser() try: sessconfig.read_file(filename) except: raise IOError("Failed to open session config file") return SessionStartupConfig(sessconfig)
def test_configparser_write_file_defaults(self): ccp = CallbackConfigParser(defaults={'foo': 'bar'}) new_path = os.path.join(self.session_base_dir, 'config_new.conf') ccp.write_file(new_path) self.assertTrue(os.path.isfile(new_path)) ccp.read_file(new_path) self.assertEqual(ccp.get('DEFAULT', 'foo'), 'bar')
def test_get_settings(self): """ Testing whether the API returns a correct settings dictionary when the settings are requested """ self.should_check_equality = False tribler_config = CallbackConfigParser() tribler_config.add_section('Tribler') tribler_config.write_file(os.path.join(self.session.get_state_dir(), 'tribler.conf')) return self.do_request('settings', expected_code=200).addCallback(self.verify_settings)
def __init__(self, dlconfig=None): super(DownloadConfigInterface, self).__init__() self.dlconfig = dlconfig or CallbackConfigParser() # Dumb^WPoor man's versioning of DownloadConfig, add missing default values. write = False for section, sect_dict in dldefaults.items(): if not self.dlconfig.has_section(section): self.dlconfig.add_section(section) for k, v in sect_dict.items(): if not self.dlconfig.has_option(section, k): write = True self.dlconfig.set(section, k, v) if write and self.dlconfig.filename: self.dlconfig.write_file()
def setupConfig(self): self.configfilepath = os.path.join(self.getConfigPath(), STATEDIR_GUICONFIG) self.config = CallbackConfigParser() # Load the config file. if os.path.exists(self.configfilepath): self.config.read_file(self.configfilepath, 'utf-8-sig') if not self.config.has_section('Tribler'): self.config.add_section('Tribler') # Tribler.conf also contains the default download config. So we need to merge it now. if not self.config.has_section('downloadconfig'): self.config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance().dlconfig._sections['downloadconfig'].iteritems(): self.config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = self.config
class SettingsEndpoint(resource.Resource): """ This endpoint is reponsible for handing all requests regarding settings and configuration. """ def __init__(self, session): resource.Resource.__init__(self) self.session = session # Load the Tribler GUI configuration file self.gui_config_file_path = os.path.join(self.session.get_state_dir(), STATEDIR_GUICONFIG) self.tribler_gui_config = CallbackConfigParser() self.tribler_gui_config.read_file(self.gui_config_file_path, 'utf-8-sig') def render_GET(self, request): """ .. http:get:: /settings A GET request to this endpoint returns all the session settings that can be found in Tribler. Please note that a port with a value of -1 means that the port is randomly assigned at startup. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/settings **Example response**: .. sourcecode:: javascript { "settings": { "libtorrent": { "anon_listen_port": -1, ... }, ... } } """ libtribler_settings = self.session.sessconfig.get_config_as_json() tribler_settings = self.tribler_gui_config.get_config_as_json() # Merge the configuration of libtribler and the Tribler configuration settings_dict = libtribler_settings.copy() settings_dict.update(tribler_settings) settings_dict["general"][ "family_filter"] = self.session.tribler_config.config["general"][ "family_filter"] return json.dumps({"settings": settings_dict}) def render_POST(self, request): """ .. http:post:: /settings A POST request to this endpoint will update Tribler settings. A JSON-dictionary should be passed as body contents. **Example request**: .. sourcecode:: none curl -X POST http://localhost:8085/settings --data "{" **Example response**: .. sourcecode:: javascript { "modified": True } """ settings_dict = json.loads(request.content.read()) self.parse_settings_dict(settings_dict) self.session.save_session_config() return json.dumps({"modified": True}) def parse_setting(self, section, option, value): """ Set a specific Tribler setting. Throw a ValueError if this setting is not available. """ if section == "general" and option == "family_filter": self.session.tribler_config.set_family_filter_enabled(value) return if section == "Tribler" or section == "downloadconfig": # Write to the Tribler GUI config file if not self.tribler_gui_config.has_option(section, option): raise ValueError("Section %s with option %s does not exist" % (section, option)) RawConfigParser.set(self.tribler_gui_config, section, option, value) self.tribler_gui_config.write_file(self.gui_config_file_path) return if not RawConfigParser.has_option(self.session.sessconfig, section, option): raise ValueError("Section %s with option %s does not exist" % (section, option)) RawConfigParser.set(self.session.sessconfig, section, option, value) # Reload the GUI settings in Tribler (there might have been download settings that have changed) self.session.setup_tribler_gui_config() # Perform some actions when specific keys are set if section == "libtorrent" and (option == "max_download_rate" or option == "max_upload_rate"): for lt_session in self.session.lm.ltmgr.ltsessions.itervalues(): ltsession_settings = lt_session.get_settings() ltsession_settings[ 'upload_rate_limit'] = self.session.get_libtorrent_max_upload_rate( ) ltsession_settings[ 'download_rate_limit'] = self.session.get_libtorrent_max_download_rate( ) lt_session.set_settings(ltsession_settings) def parse_settings_dict(self, settings_dict, depth=1, root_key=None): """ Parse the settings dictionary. Throws an error if the options dictionary seems to be invalid (i.e. there are keys not available in the configuration or the depth of the dictionary is too high. """ if depth == 3: raise ValueError("Invalid settings dictionary depth (%d)" % depth) for key, value in settings_dict.iteritems(): if isinstance(value, dict): self.parse_settings_dict(value, depth=depth + 1, root_key=key) else: self.parse_setting(root_key, key, value)
def load_download_pstate(self, filename): """ Called by any thread """ pstate = CallbackConfigParser() pstate.read_file(filename) return pstate
def test_startup_session_save_load(self): sci = SessionStartupConfig(CallbackConfigParser()) file_path = os.path.join(self.session_base_dir, "startupconfig.conf") sci.save(file_path) sci.load(file_path)
def test_session_config_init(self): sessconf = CallbackConfigParser() sessconf.add_section('mainline_dht') sessconf.set('mainline_dht', 'mainline_dht_port', 1234) sci = SessionConfigInterface(sessconf) self.assertTrue(sci) self.assertIsInstance(sci.get_listen_port(), int) self.assertIsInstance(sci.get_mainline_dht_listen_port(), int) self.assertIsInstance(sci.get_default_state_dir(), unicode) sci.set_state_dir(self.session_base_dir) self.assertEqual(sci.get_state_dir(), self.session_base_dir) default_log_dir = os.path.join(self.session_base_dir, "logs") self.assertEqual(sci.get_log_dir(), default_log_dir) sci.set_log_dir(self.LOG_DIR) self.assertEqual(sci.get_log_dir(), self.LOG_DIR) self.assertIsInstance(sci.get_install_dir(), (unicode, str)) self.assertIsInstance(sci.get_permid_keypair_filename(), str) sci.set_listen_port(1337) self.assertEqual(sci.sessconfig.get('general', 'minport'), 1337) self.assertEqual(sci.sessconfig.get('general', 'maxport'), 1337) self.assertIsInstance(sci.get_tunnel_community_socks5_listen_ports(), list) self.assertFalse(sci.get_tunnel_community_exitnode_enabled()) sci.set_tunnel_community_enabled(False) self.assertFalse(sci.get_tunnel_community_enabled()) sci.set_megacache(False) self.assertFalse(sci.get_megacache()) sci.set_libtorrent(False) self.assertFalse(sci.get_libtorrent()) sci.set_libtorrent_max_conn_download(5) self.assertEqual(sci.get_libtorrent_max_conn_download(), 5) sci.set_libtorrent_max_download_rate(200) self.assertEqual(sci.get_libtorrent_max_download_rate(), 200) sci.set_libtorrent_max_upload_rate(300) self.assertEqual(sci.get_libtorrent_max_upload_rate(), 300) sci.set_libtorrent_proxy_settings(3, ("127.0.0.1", 1337), ("foo", "bar")) self.assertEqual(sci.get_libtorrent_proxy_settings(), (3, ("127.0.0.1", 1337), ("foo", "bar"))) sci.set_anon_proxy_settings(5, ("127.0.0.1", 1337), ("foo", "bar")) self.assertEqual(sci.get_anon_proxy_settings(), (5, ("127.0.0.1", 1337), ("foo", "bar"))) sci.set_libtorrent_utp(False) self.assertFalse(sci.get_libtorrent_utp()) sci.set_torrent_store(False) self.assertFalse(sci.get_torrent_store()) sci.set_torrent_store_dir(self.session_base_dir) self.assertEqual(sci.get_torrent_store_dir(), self.session_base_dir) sci.set_torrent_collecting(False) self.assertFalse(sci.get_torrent_collecting()) sci.set_dht_torrent_collecting(False) self.assertFalse(sci.get_dht_torrent_collecting()) sci.set_torrent_collecting_max_torrents(1337) self.assertEqual(sci.get_torrent_collecting_max_torrents(), 1337) sci.set_torrent_collecting_dir(self.session_base_dir) self.assertEqual(sci.get_torrent_collecting_dir(), self.session_base_dir) sci.set_torrent_checking(False) self.assertFalse(sci.get_torrent_checking()) sci.set_stop_collecting_threshold(1337) self.assertEqual(sci.get_stop_collecting_threshold(), 1337) sci.set_nickname("foobar") self.assertEqual(sci.get_nickname(), "foobar") self.assertEqual(sci.get_mugshot(), (None, None)) sci.set_mugshot("myimage", mime="image/png") self.assertEqual(sci.get_mugshot(), ("image/png", "myimage")) sci.set_peer_icon_path(self.session_base_dir) self.assertEqual(sci.get_peer_icon_path(), self.session_base_dir) sci.set_video_analyser_path(self.session_base_dir) self.assertEqual(sci.get_video_analyser_path(), self.session_base_dir) sci.set_mainline_dht(False) self.assertFalse(sci.get_mainline_dht()) sci.set_mainline_dht_listen_port(1337) self.assertEqual( sci.sessconfig.get('mainline_dht', 'mainline_dht_port'), 1337) sci.set_multicast_local_peer_discovery(False) self.assertFalse(sci.get_multicast_local_peer_discovery()) sci.set_dispersy(False) self.assertFalse(sci.get_dispersy()) sci.set_dispersy_port(1337) self.assertIsInstance(sci.get_dispersy_port(), int) self.assertEqual(sci.sessconfig.get('dispersy', 'dispersy_port'), 1337) sci.set_videoserver_enabled(False) self.assertFalse(sci.get_videoserver_enabled()) sci.set_videoplayer_path(self.session_base_dir) self.assertEqual(sci.get_videoplayer_path(), self.session_base_dir) sci.set_videoserver_port(1337) self.assertIsInstance(sci.get_videoserver_port(), int) self.assertEqual(sci.sessconfig.get('video', 'port'), 1337) sci.set_preferred_playback_mode(5) self.assertEqual(sci.get_preferred_playback_mode(), 5) sci.set_enable_torrent_search(False) self.assertFalse(sci.get_enable_torrent_search()) sci.set_enable_channel_search(False) self.assertFalse(sci.get_enable_channel_search()) sci.set_enable_metadata(False) self.assertFalse(sci.get_enable_metadata()) sci.set_metadata_store_dir(self.session_base_dir) self.assertEqual(sci.get_metadata_store_dir(), self.session_base_dir) sci.set_channel_community_enabled(False) self.assertFalse(sci.get_channel_community_enabled()) sci.set_preview_channel_community_enabled(False) self.assertFalse(sci.get_preview_channel_community_enabled()) sci.set_http_api_enabled(True) self.assertTrue(sci.get_http_api_enabled()) sci.set_http_api_port(1337) self.assertEqual(sci.sessconfig.get('http_api', 'port'), 1337) sci.set_resource_monitor_enabled(False) self.assertFalse(sci.get_resource_monitor_enabled()) sci.set_resource_monitor_poll_interval(12) self.assertEqual(sci.get_resource_monitor_poll_interval(), 12) sci.set_resource_monitor_history_size(1234) self.assertEqual(sci.get_resource_monitor_history_size(), 1234) self.assertIsInstance( sci.get_default_config_filename(self.session_base_dir), str)
def copy(self): config = CallbackConfigParser() config._sections = {'download_defaults': copy.deepcopy(self.dlconfig._sections['download_defaults'])} return DownloadStartupConfig(config)
def load(filename): dlconfig = CallbackConfigParser() dlconfig.read_file(filename) return DefaultDownloadStartupConfig(dlconfig)
def __init__(self, sessconfig=None): """ Constructor. @param sessconfig Optional dictionary used internally to make this a copy constructor. """ self._logger = logging.getLogger(self.__class__.__name__) self.selected_ports = {} self.sessconfig = sessconfig or CallbackConfigParser() # Poor man's versioning of SessionConfig, add missing default values. for section, sect_dict in sessdefaults.iteritems(): if not self.sessconfig.has_section(section): self.sessconfig.add_section(section) for k, v in sect_dict.iteritems(): if not self.sessconfig.has_option(section, k): self.sessconfig.set(section, k, v) if not sessconfig: return # Set video_analyser_path if sys.platform == 'win32': ffmpegname = u"ffmpeg.exe" elif sys.platform == 'darwin': ffmpegname = u"ffmpeg" elif find_executable("avconv"): ffmpegname = u"avconv" else: ffmpegname = u"ffmpeg" ffmpegpath = find_executable(ffmpegname) if ffmpegpath is None: if sys.platform == 'darwin': self.sessconfig.set(u'general', u'videoanalyserpath', u"vlc/ffmpeg") elif is_android(strict=True): self.sessconfig.set( u'general', u'videoanalyserpath', os.path.join(os.environ['ANDROID_PRIVATE'], 'ffmpeg')) else: self.sessconfig.set(u'general', u'videoanalyserpath', ffmpegname) else: self.sessconfig.set(u'general', u'videoanalyserpath', ffmpegpath) # Set videoplayer path if sys.platform == 'win32': videoplayerpath = os.path.expandvars( '${PROGRAMFILES}') + '\\Windows Media Player\\wmplayer.exe' elif sys.platform == 'darwin': videoplayerpath = find_executable("vlc") or ( "/Applications/VLC.app" if os.path.exists("/Applications/VLC.app") else None) or "/Applications/QuickTime Player.app" else: videoplayerpath = find_executable("vlc") or "vlc" self.sessconfig.set(u'video', u'path', videoplayerpath) self.sessconfig.set(u'general', u'ipv6_binds_v4', autodetect_socket_style())
class Utility(object): def __init__(self, abcpath, configpath, app=None, session=None): self.version = version_id self.abcpath = abcpath # Find the directory to save config files, etc. self.dir_root = configpath self.setupConfig() # Is ABC in the process of shutting down? self.abcquitting = False self.app = app self.session = session def setupConfig(self): self.configfilepath = os.path.join(self.getConfigPath(), STATEDIR_GUICONFIG) self.config = CallbackConfigParser() # Load the config file. if os.path.exists(self.configfilepath): self.config.read_file(self.configfilepath, 'utf-8-sig') if not self.config.has_section('Tribler'): self.config.add_section('Tribler') # Tribler.conf also contains the default download config. So we need to merge it now. if not self.config.has_section('downloadconfig'): self.config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance( ).dlconfig._sections['downloadconfig'].iteritems(): self.config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = self.config def getVersion(self): return self.version def getConfigPath(self): return self.dir_root def getPath(self): return self.abcpath def set_session(self, session): self.session = session def set_app(self, app): self.app = app def read_config(self, option, section='Tribler', literal_eval=True): if not self.config.has_option(section, option): return tribler_defaults.get(section, {}).get(option, None) return self.config.get(section, option, literal_eval=literal_eval) def write_config(self, option, value, section='Tribler', flush=True): self.config.set(section, option, value) if flush: self.flush_config() def flush_config(self): self.config.write_file(self.configfilepath)
def test_configparser_set_callback(self): def parser_callback(section, option, old_value, new_value): return True ccp = CallbackConfigParser() ccp.set_callback(parser_callback) ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) ccp.set('search_community', 'enabled', False) ccp.set('search_community', 'bar', 42) self.assertFalse(ccp.get('search_community', 'enabled')) self.assertEquals(ccp.get('search_community', 'bar'), 42)
def load(filename): dlconfig = CallbackConfigParser() dlconfig.read_file(filename) return DefaultDownloadStartupConfig(dlconfig)
def test_configparser_set_callback(self): def parser_callback(section, option, old_value, new_value): return True ccp = CallbackConfigParser() ccp.set_callback(parser_callback) ccp.read_file(os.path.join(self.CONFIG_FILES_DIR, 'config1.conf')) ccp.set('search_community', 'enabled', False) ccp.set('search_community', 'bar', 42) self.assertFalse(ccp.get('search_community', 'enabled')) self.assertEquals(ccp.get('search_community', 'bar'), 42)
class Utility(object): def __init__(self, abcpath, configpath, app=None, session=None): self.version = version_id self.abcpath = abcpath # Find the directory to save config files, etc. self.dir_root = configpath self.setupConfig() # Is ABC in the process of shutting down? self.abcquitting = False self.app = app self.session = session def setupConfig(self): self.configfilepath = os.path.join(self.getConfigPath(), STATEDIR_GUICONFIG) self.config = CallbackConfigParser() # Load the config file. if os.path.exists(self.configfilepath): self.config.read_file(self.configfilepath, 'utf-8-sig') if not self.config.has_section('Tribler'): self.config.add_section('Tribler') # Tribler.conf also contains the default download config. So we need to merge it now. if not self.config.has_section('downloadconfig'): self.config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance().dlconfig._sections['downloadconfig'].iteritems(): self.config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = self.config def getVersion(self): return self.version def getConfigPath(self): return self.dir_root def getPath(self): return self.abcpath def set_session(self, session): self.session = session def set_app(self, app): self.app = app def read_config(self, option, section='Tribler', literal_eval=True): if not self.config.has_option(section, option): return tribler_defaults.get(section, {}).get(option, None) return self.config.get(section, option, literal_eval=literal_eval) def write_config(self, option, value, section='Tribler', flush=True): self.config.set(section, option, value) if flush: self.flush_config() def flush_config(self): self.config.write_file(self.configfilepath)
def __init__(self, sessconfig=None): """ Constructor. @param sessconfig Optional dictionary used internally to make this a copy constructor. """ self._logger = logging.getLogger(self.__class__.__name__) self.selected_ports = {} self.sessconfig = sessconfig or CallbackConfigParser() # Poor man's versioning of SessionConfig, add missing default values. for section, sect_dict in sessdefaults.iteritems(): if not self.sessconfig.has_section(section): self.sessconfig.add_section(section) for k, v in sect_dict.iteritems(): if not self.sessconfig.has_option(section, k): self.sessconfig.set(section, k, v) if not sessconfig: return if sys.platform == 'win32': # TODO(emilon): This is to work around the case where windows has # non-ASCI chars on %PATH% contents. Should be removed if we migrate to # python 3. from Tribler.Main.hacks import get_environment_variable path_env = get_environment_variable(u"PATH") elif is_android(): path_env = unicode(os.environ["PYTHONPATH"]) else: path_env = os.environ["PATH"] # Set video_analyser_path if sys.platform == 'win32': ffmpegname = u"ffmpeg.exe" elif sys.platform == 'darwin': ffmpegname = u"ffmpeg" elif find_executable("avconv", path_env): ffmpegname = u"avconv" else: ffmpegname = u"ffmpeg" ffmpegpath = find_executable(ffmpegname, path_env) if ffmpegpath is None: if sys.platform == 'darwin': self.sessconfig.set(u'general', u'videoanalyserpath', u"vlc/ffmpeg") else: self.sessconfig.set(u'general', u'videoanalyserpath', os.path.abspath(ffmpegname)) else: self.sessconfig.set(u'general', u'videoanalyserpath', os.path.abspath(ffmpegpath)) # Set videoplayer path if sys.platform == 'win32': videoplayerpath = os.path.expandvars( '${PROGRAMFILES}') + '\\Windows Media Player\\wmplayer.exe' elif sys.platform == 'darwin': videoplayerpath = find_executable("vlc") or ( "/Applications/VLC.app" if os.path.exists("/Applications/VLC.app") else None) or "/Applications/QuickTime Player.app" else: videoplayerpath = find_executable("vlc") or "vlc" self.sessconfig.set(u'video', u'path', videoplayerpath) self.sessconfig.set(u'general', u'ipv6_binds_v4', autodetect_socket_style())
def load_download_pstate(self, filename): """ Called by any thread """ pstate = CallbackConfigParser() pstate.read_file(filename) return pstate
def setup_tribler_gui_config(self): """ Initialize the TriblerGUI configuration file and make sure that we have all required values. """ configfilepath = os.path.join(self.get_state_dir(), STATEDIR_GUICONFIG) gui_config = CallbackConfigParser() DefaultDownloadStartupConfig.getInstance().set_dest_dir( get_default_dest_dir()) # Load the config file. if os.path.exists(configfilepath): gui_config.read_file(configfilepath, 'utf-8-sig') if not gui_config.has_section('Tribler'): gui_config.add_section('Tribler') for k, v in tribler_defaults['Tribler'].iteritems(): if not gui_config.has_option('Tribler', k): gui_config.set('Tribler', k, v) if not gui_config.has_section('downloadconfig'): gui_config.add_section('downloadconfig') for k, v in DefaultDownloadStartupConfig.getInstance( ).dlconfig._sections['downloadconfig'].iteritems(): if not gui_config.has_option('downloadconfig', k): gui_config.set('downloadconfig', k, v) # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig. DefaultDownloadStartupConfig.getInstance().dlconfig = gui_config gui_config.write_file(configfilepath) # Update all dldefaults to use the settings in gui_config for k, v in gui_config._sections['downloadconfig'].iteritems(): dldefaults['downloadconfig'][k] = v