Beispiel #1
0
def check_keyring_support():
	"""
	Check if the UserNamePassword class can be used,
	else raise ImportError with an explanatory error message.
	"""
	global keyring
	# if gnomekeyring exists, block kde libraries
	old_pykde4 = sys.modules.get('PyKDE4')
	try:
		import gnomekeyring
	except ImportError:
		pass
	else:
		sys.modules['PyKDE4'] = None
	try:
		import keyring
	except ImportError:
		global UserNamePassword
		class UserNamePassword (object):
			pass
		raise
	else:
		# Configure the fallback keyring's configuration file if used
		import keyring.backend
		kr = keyring.get_keyring()
		if hasattr(kr, "crypted_password"):
			keyring.set_keyring(keyring.backend.UncryptedFileKeyring())
			kr = keyring.get_keyring()
		if hasattr(kr, "file_path"):
			kr.file_path = config.save_config_file("keyring.cfg")
	finally:
		# now unblock kde libraries again
		if old_pykde4:
			sys.modules['PyKDE4'] = old_pykde4
Beispiel #2
0
	def make_help_text():
		from kupfer import config

		config_filename = "kupfer.cfg"
		defaults_filename = "defaults.cfg"
		conf_path = config.save_config_file(config_filename)
		defaults_path = config.get_data_file(defaults_filename)
		usage_string = _("Usage: kupfer [OPTIONS | QUERY]")
		def format_options(opts):
			return "\n".join("  --%-15s  %s" % (o,h) for o,h in opts)

		options_string = u"%s\n\n%s\n\n%s" % (usage_string,
				format_options(program_options), format_options(misc_options))

		configure_help1 = _("To configure kupfer, edit:")
		configure_help2 = _("The default config for reference is at:")
		help_text = "\n".join((
			options_string,
			"\n",
			configure_help1,
			"\t%s" % conf_path,
			configure_help2,
			"\t%s" % defaults_path,
			"\n",
		))
		return help_text
Beispiel #3
0
	def _configure_keyring(cls):
		# Configure the fallback keyring's configuration file if used
		import keyring.backend
		kr = keyring.get_keyring()
		if hasattr(kr, "crypted_password"):
			keyring.set_keyring(keyring.backend.UncryptedFileKeyring())
			kr = keyring.get_keyring()
		if hasattr(kr, "file_path"):
			kr.file_path = config.save_config_file("keyring.cfg")
Beispiel #4
0
def save():
    """
	Save the learning record
	"""
    if not _register:
        pretty.print_debug(__name__, "Not writing empty register")
        return
    if len(_register) > 100:
        _prune_register()
    filepath = config.save_config_file(mnemonics_filename)
    Learning._pickle_register(_register, filepath)
Beispiel #5
0
def save():
    """
    Save the learning record
    """
    if not _register:
        pretty.print_debug(__name__, "Not writing empty register")
        return
    if len(_register) > 100:
        _prune_register()
    filepath = config.save_config_file(mnemonics_filename)
    Learning._pickle_register(_register, filepath)
Beispiel #6
0
    def _save_config(self, scheduler=None):
        self.output_debug("Saving config")
        config_path = config.save_config_file(self.config_filename)
        if not config_path:
            self.output_info("Unable to save settings, can't find config dir")
            return
        # read in just the default values
        default_confmap = self._read_config(read_config=False)

        def confmap_difference(config, defaults):
            """Extract the non-default keys to write out"""
            difference = dict()
            for secname, section in list(config.items()):
                if secname not in defaults:
                    difference[secname] = dict(section)
                    continue
                difference[secname] = {}
                for key, config_val in list(section.items()):
                    if (secname in defaults and key in defaults[secname]):
                        if defaults[secname][key] == config_val:
                            continue
                    difference[secname][key] = config_val
                if not difference[secname]:
                    del difference[secname]
            return difference

        parser = configparser.RawConfigParser()

        def fill_parser(parser, defaults):
            for secname in sorted(defaults):
                section = defaults[secname]
                if not parser.has_section(secname):
                    parser.add_section(secname)
                for key in sorted(section):
                    value = section[key]
                    if isinstance(value, (tuple, list)):
                        value = self.sep.join(value)
                    elif isinstance(value, int):
                        value = str(value)
                    parser.set(secname, key, value)

        confmap = confmap_difference(self._config, default_confmap)
        fill_parser(parser, confmap)
        ## Write to tmp then rename over for it to be atomic
        temp_config_path = "%s.%s" % (config_path, os.getpid())
        with open(temp_config_path, "w") as out:
            parser.write(out)
        os.rename(temp_config_path, config_path)
Beispiel #7
0
    def _save_config(self, scheduler=None):
        self.output_debug("Saving config")
        config_path = config.save_config_file(self.config_filename)
        if not config_path:
            self.output_info("Unable to save settings, can't find config dir")
            return
  # read in just the default values
        default_confmap = self._read_config(read_config=False)

        def confmap_difference(config, defaults):
            """Extract the non-default keys to write out"""
            difference = dict()
            for secname, section in config.items():
                if secname not in defaults:
                    difference[secname] = dict(section)
                    continue
                difference[secname] = {}
                for key, config_val in section.items():
                    if (secname in defaults and
                            key in defaults[secname]):
                        if defaults[secname][key] == config_val:
                            continue
                    difference[secname][key] = config_val
                if not difference[secname]:
                    del difference[secname]
            return difference

        parser = ConfigParser.SafeConfigParser()

        def fill_parser(parser, defaults):
            for secname, section in defaults.iteritems():
                if not parser.has_section(secname):
                    parser.add_section(secname)
                for key, default in section.iteritems():
                    if isinstance(default, (tuple, list)):
                        default = self.sep.join(default)
                    elif isinstance(default, int):
                        default = str(default)
                    parser.set(secname, key, default)

        confmap = confmap_difference(self._config, default_confmap)
        fill_parser(parser, confmap)
        ## Write to tmp then rename over for it to be atomic
        temp_config_path = "%s.%s" % (config_path, os.getpid())
        with open(temp_config_path, "w") as out:
            parser.write(out)
        os.rename(temp_config_path, config_path)
Beispiel #8
0
def check_keyring_support():
    """
	Check if the UserNamePassword class can be used,
	else raise ImportError with an explanatory error message.
	"""
    global keyring
    # if gnomekeyring exists, block kde libraries
    old_pykde4 = sys.modules.get('PyKDE4')
    try:
        import gnomekeyring
    except ImportError:
        pass
    else:
        sys.modules['PyKDE4'] = None
    try:
        import keyring
    except ImportError:
        global UserNamePassword

        class UserNamePassword(object):
            pass

        raise
    else:
        # Configure the fallback keyring's configuration file if used
        import keyring.backend
        kr = keyring.get_keyring()
        if hasattr(kr, "crypted_password"):
            keyring.set_keyring(keyring.backend.UncryptedFileKeyring())
            kr = keyring.get_keyring()
        if hasattr(kr, "file_path"):
            kr.file_path = config.save_config_file("keyring.cfg")
    finally:
        # now unblock kde libraries again
        if old_pykde4:
            sys.modules['PyKDE4'] = old_pykde4
Beispiel #9
0
	def _configure_keyring(cls):
		# Configure the fallback keyring's configuration file if used
		kr = keyring.get_keyring()
		if hasattr(kr, "file_path"):
			kr.file_path = config.save_config_file("keyring.cfg")
Beispiel #10
0
	def get_filename(cls, source):
		"""Return filename for @source"""
		name = source.config_save_name()
		filename = cls.name_template % (name, cls.pickle_version)
		return config.save_config_file(filename)
def get_keyring():
	""" Get one of working keyrings. """
	global _KEYRING
	if _KEYRING is not None:  # keyring configured
		return _KEYRING
	global _KEYRING_NAME
	try:
		import gnomekeyring
		if gnomekeyring.is_available():
			# create fake keyring as long way by keyring module not work without
			# gi.
			class FakeGnomeKeyring:
				""" Proxy class emulate standard interface for Gnome Keyring. """
				@staticmethod
				def get_password(plugin_id, username):
					kr_name = gnomekeyring.get_default_keyring_sync()
					for id_ in gnomekeyring.list_item_ids_sync(kr_name):
						attrs = gnomekeyring.item_get_attributes_sync(kr_name,
								id_)
						if (attrs.get('plugin_id') == plugin_id
								and attrs.get('username') == username):
							return gnomekeyring.item_get_info_sync(kr_name,
									id_).get_secret()

				@staticmethod
				def set_password(plugin_id, username, password):
					kr_name = gnomekeyring.get_default_keyring_sync()
					attrs = {'username': username, 'plugin_id': plugin_id}
					gnomekeyring.item_create_sync(kr_name,
							gnomekeyring.ITEM_GENERIC_SECRET,
							_("Password for %s in %s (Kupfer)") % (username,
								plugin_id),
							attrs, password, True)

				@staticmethod
				def supported():
					return 1

			_KEYRING = FakeGnomeKeyring
			_KEYRING_NAME = _("GNOME Keyring")
			return _KEYRING
	except ImportError:
		pass

	import keyring
	import keyring.backends
	kr = None
	try:
		from keyring.backend.GnomeKeyring import Keyring
		kr = Keyring()
	except ImportError:
		try:
			from keyring.backend import GnomeKeyring
			kr = GnomeKeyring()
		except ImportError:
			pretty.print_error(__name__, "GnomeKeyring not found")

	if kr:
		keyring.set_keyring(kr)
		_KEYRING_NAME = _("GNOME Keyring")
		_KEYRING = kr
		return kr

	try:
		from keyring.backend.kwallet import Keyring
		kr = Keyring()
	except ImportError:
		try:
			from keyring.backend import KDEKWallet
			kr = KDEKWallet()
		except ImportError:
			pretty.print_error(__name__, "KDEKWallet not found")

	if kr:
		keyring.set_keyring(kr)
		_KEYRING_NAME = _("KWallet")
		_KEYRING = kr
		return kr

	kr = keyring.get_keyring()
	if hasattr(kr, "crypted_password"):
		UncryptedFileKeyring = None
		try:
			from keyring.backends.file import PlaintextKeyring as UncryptedFileKeyring
		except ImportError:
			from keyring.backend import UncryptedFileKeyring
		keyring.set_keyring(UncryptedFileKeyring())
		kr = keyring.get_keyring()
	if hasattr(kr, "file_path"):
		kr.file_path = config.save_config_file("keyring.cfg")
	_KEYRING_NAME = _("Unencrypted File")
	_KEYRING = kr
	return kr
Beispiel #12
0
def get_keyring():
    """ Get one of working keyrings. """
    global _KEYRING
    if _KEYRING is not None:  # keyring configured
        return _KEYRING
    global _KEYRING_NAME
    try:
        import gnomekeyring
        if gnomekeyring.is_available():
            # create fake keyring as long way by keyring module not work without
            # gi.
            class FakeGnomeKeyring:
                """ Proxy class emulate standard interface for Gnome Keyring. """
                @staticmethod
                def get_password(plugin_id, username):
                    kr_name = gnomekeyring.get_default_keyring_sync()
                    for id_ in gnomekeyring.list_item_ids_sync(kr_name):
                        attrs = gnomekeyring.item_get_attributes_sync(
                            kr_name, id_)
                        if (attrs.get('plugin_id') == plugin_id
                                and attrs.get('username') == username):
                            return gnomekeyring.item_get_info_sync(
                                kr_name, id_).get_secret()

                @staticmethod
                def set_password(plugin_id, username, password):
                    kr_name = gnomekeyring.get_default_keyring_sync()
                    attrs = {'username': username, 'plugin_id': plugin_id}
                    gnomekeyring.item_create_sync(
                        kr_name, gnomekeyring.ITEM_GENERIC_SECRET,
                        _("Password for %s in %s (Kupfer)") %
                        (username, plugin_id), attrs, password, True)

                @staticmethod
                def supported():
                    return 1

            _KEYRING = FakeGnomeKeyring
            _KEYRING_NAME = _("GNOME Keyring")
            return _KEYRING
    except ImportError:
        pass

    import keyring
    import keyring.backends
    kr = None
    try:
        from keyring.backend.GnomeKeyring import Keyring
        kr = Keyring()
    except ImportError:
        try:
            from keyring.backend import GnomeKeyring
            kr = GnomeKeyring()
        except ImportError:
            pretty.print_error(__name__, "GnomeKeyring not found")

    if kr:
        keyring.set_keyring(kr)
        _KEYRING_NAME = _("GNOME Keyring")
        _KEYRING = kr
        return kr

    try:
        from keyring.backend.kwallet import Keyring
        kr = Keyring()
    except ImportError:
        try:
            from keyring.backend import KDEKWallet
            kr = KDEKWallet()
        except ImportError:
            pretty.print_error(__name__, "KDEKWallet not found")

    if kr:
        keyring.set_keyring(kr)
        _KEYRING_NAME = _("KWallet")
        _KEYRING = kr
        return kr

    kr = keyring.get_keyring()
    if hasattr(kr, "crypted_password"):
        UncryptedFileKeyring = None
        try:
            from keyring.backends.file import PlaintextKeyring as UncryptedFileKeyring
        except ImportError:
            from keyring.backend import UncryptedFileKeyring
        keyring.set_keyring(UncryptedFileKeyring())
        kr = keyring.get_keyring()
    if hasattr(kr, "file_path"):
        kr.file_path = config.save_config_file("keyring.cfg")
    _KEYRING_NAME = _("Unencrypted File")
    _KEYRING = kr
    return kr
Beispiel #13
0
 def _filename(self):
     ret = config.save_config_file("action_accels.json")
     if ret is None:
         self.output_error("Can't find XDG_CONFIG_HOME")
     return ret
Beispiel #14
0
 def get_filename(cls, source):
     """Return filename for @source"""
     name = source.config_save_name()
     filename = cls.name_template % (name, cls.format_version)
     return config.save_config_file(filename)