Пример #1
0
    def __handle_import_option(self, value, family_tree_format):
        """
        Handle the "-i" or "--import" option.
        Only Files supported by a plugin can be imported, so not Family Trees.
        """
        # Need to convert path/filename to unicode before openingh
        # For non latin characters in Windows path/file/user names
        value = Utils.get_unicode_path_from_env_var(value)
        fname = value
        fullpath = os.path.abspath(os.path.expanduser(fname))
        if not os.path.exists(fullpath):
            self.__error(_('Error: Import file %s not found.') % fname)
            sys.exit(0)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_import_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True

        if plugin_found:
            self.imports.append((fname, family_tree_format))
        else:
            self.__error(_('Error: Unrecognized type: "%(format)s" for '
                    'import file: %(filename)s') \
                  % {'format' : family_tree_format,
                     'filename' : fname})
            sys.exit(0)
Пример #2
0
    def import_new_db(self, filename, callback):
        """
        Attempt to import the provided file into a new database.
        A new database will only be created if an appropriate importer was 
        found.
        
        @return: A tuple of (new_path, name) for the new database
                 or (None, None) if no import was performed.
        """
        pmgr = BasePluginManager.get_instance()
        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                new_path, name = self._create_new_db(name)

                # Create a new database
                self.__start_cursor(_("Importing data..."))
                dbclass = gen.db.DbBsddb
                dbase = dbclass()
                dbase.load(new_path, callback)

                import_function = plugin.get_import_function()
                import_function(dbase, filename, callback)

                # finish up
                self.__end_cursor()
                dbase.close()

                return new_path, name
        return None, None
Пример #3
0
    def import_new_db(self, filename, callback):
        """
        Attempt to import the provided file into a new database.
        A new database will only be created if an appropriate importer was 
        found.
        
        @return: A tuple of (new_path, name) for the new database
                 or (None, None) if no import was performed.
        """
        pmgr = BasePluginManager.get_instance()
        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                new_path, name = self._create_new_db(name)
    
                # Create a new database
                self.__start_cursor(_("Importing data..."))
                dbclass = gen.db.DbBsddb
                dbase = dbclass()
                dbase.load(new_path, callback)
    
                import_function = plugin.get_import_function()
                import_function(dbase, filename, callback)
    
                # finish up
                self.__end_cursor()
                dbase.close()
                
                return new_path, name
        return None, None
Пример #4
0
    def __handle_import_option(self, value, family_tree_format):
        """
        Handle the "-i" or "--import" option.
        Only Files supported by a plugin can be imported, so not Family Trees.
        """
        # Need to convert path/filename to unicode before openingh
		# For non latin characters in Windows path/file/user names
        value = Utils.get_unicode_path_from_env_var(value)
        fname = value
        fullpath = os.path.abspath(os.path.expanduser(fname))
        if not os.path.exists(fullpath):
            self.__error(_('Error: Import file %s not found.') % fname)
            sys.exit(0)
        
        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period, 
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_import_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True
                
        if plugin_found:
            self.imports.append((fname, family_tree_format))
        else:
            self.__error(_('Error: Unrecognized type: "%(format)s" for '
                    'import file: %(filename)s') \
                  % {'format' : family_tree_format, 
                     'filename' : fname})
            sys.exit(0)
Пример #5
0
 def __init__(self, dbstate, setloader):
     self.dbstate = dbstate
     if setloader:
         self.db_loader = CLIDbLoader(self.dbstate)
     else:
         self.db_loader = None
     self.file_loaded = False
     self._pmgr = BasePluginManager.get_instance()
Пример #6
0
 def cl_import(self, filename, family_tree_format):
     """
     Command-line import routine.
     Try to import filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_import_plugins():
         if family_tree_format == plugin.get_extension():
             import_function = plugin.get_import_function()
             import_function(self.dbstate.db, filename, None)
Пример #7
0
 def cl_export(self, filename, family_tree_format):
     """
     Command-line export routine. 
     Try to write into filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_export_plugins():
         if family_tree_format == plugin.get_extension():
             export_function = plugin.get_export_function()
             export_function(self.dbstate.db, filename, self.__error)
Пример #8
0
    def __init__(self):
        """ This function should only be run once by get_instance() """
        if GuiPluginManager.__instance is not 1:
            raise Exception("This class is a singleton. "
                            "Use the get_instance() method")

        gen.utils.Callback.__init__(self)
        self.basemgr = BasePluginManager.get_instance()
        self.__hidden_plugins = set(config.get('plugin.hiddenplugins'))
        self.__hidden_changed()
Пример #9
0
 def cl_export(self, filename, family_tree_format):
     """
     Command-line export routine. 
     Try to write into filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_export_plugins():
         if family_tree_format == plugin.get_extension():
             export_function = plugin.get_export_function()
             export_function(self.dbstate.db, filename)
Пример #10
0
    def import_new_db(self, filename, callback):
        """
        Attempt to import the provided file into a new database.
        A new database will only be created if an appropriate importer was 
        found.
        
        @return: A tuple of (new_path, name) for the new database
                 or (None, None) if no import was performed.
        """
        pmgr = BasePluginManager.get_instance()
        # check to see if it isn't a filename directly:
        if not os.path.isfile(filename):
            # Allow URL names here; make temp file if necessary
            url = urlparse.urlparse(filename)
            if url.scheme != "":
                if url.scheme == "file":
                    filename = urllib2.url2pathname(filename[7:])
                else:
                    url_fp = urllib2.urlopen(filename)  # open URL
                    # make a temp local file:
                    ext = os.path.splitext(url.path)[1]
                    fd, filename = tempfile.mkstemp(suffix=ext)
                    temp_fp = os.fdopen(fd, "w")
                    # read from URL:
                    data = url_fp.read()
                    # write locally:
                    temp_fp.write(data)
                    url_fp.close()
                    temp_fp.close()

        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                new_path, name = self._create_new_db(name)

                # Create a new database
                self.__start_cursor(_("Importing data..."))
                dbclass = gen.db.DbBsddb
                dbase = dbclass()
                dbase.write_version(new_path)
                dbase.load(new_path, callback)

                import_function = plugin.get_import_function()
                import_function(dbase, filename, callback)

                # finish up
                self.__end_cursor()
                dbase.close()

                return new_path, name
        return None, None
Пример #11
0
    def __handle_export_option(self, value, family_tree_format):
        """
        Handle the "-e" or "--export" option.  
        Note: this can only happen in the CLI version.                    
        """
        if self.gui:
            return
        # Need to convert path/filename to unicode before opening
        # For non latin characters in Windows path/file/user names
        value = Utils.get_unicode_path_from_env_var(value)
        fname = value
        if fname == '-':
            fullpath = '-'
        else:
            fullpath = os.path.abspath(os.path.expanduser(fname))
            if os.path.exists(fullpath):
                self.__error(
                    _("WARNING: Output file already exists!\n"
                      "WARNING: It will be overwritten:\n   %s") % fullpath)
                try:
                    answer = raw_input(_('OK to overwrite? (yes/no) ') \
                                         .encode(sys.getfilesystemencoding()))
                except EOFError:
                    print
                    sys.exit(0)
                if answer.upper() in ('Y', 'YES', _('YES').upper()):
                    self.__error(
                        _("Will overwrite the existing file: %s") % fullpath)
                else:
                    sys.exit(0)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_export_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True

        if plugin_found:
            self.exports.append((fullpath, family_tree_format))
        else:
            self.__error(
                _("ERROR: Unrecognized format for export file %s") % fname)
            sys.exit(0)
Пример #12
0
 def cl_import(self, filename, family_tree_format):
     """
     Command-line import routine. Try to import filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_import_plugins():
         if family_tree_format == plugin.get_extension():
             import_function = plugin.get_import_function()
             import_function(self.dbstate.db, filename, None)
     
     if not self.cl:
         if self.imp_db_path:
             return self.sm.open_activate(self.imp_db_path)
         else:
             return self.sm.open_activate(self.open)
Пример #13
0
    def cl_import(self, filename, family_tree_format):
        """
        Command-line import routine. Try to import filename using the family_tree_format.
        """
        pmgr = BasePluginManager.get_instance()
        for plugin in pmgr.get_import_plugins():
            if family_tree_format == plugin.get_extension():
                import_function = plugin.get_import_function()
                import_function(self.dbstate.db, filename, None)

        if not self.cl:
            if self.imp_db_path:
                return self.sm.open_activate(self.imp_db_path)
            else:
                return self.sm.open_activate(self.open)
Пример #14
0
    def __handle_export_option(self, value, family_tree_format):
        """
        Handle the "-e" or "--export" option.  
        Note: this can only happen in the CLI version.                    
        """
        if self.gui:
            return
        # Need to covert path/filename to unicode before openingh
		# For non latin characters in Windows path/file/user names
        value = Utils.get_unicode_path_from_env_var(value)
        fname = value
        fullpath = os.path.abspath(os.path.expanduser(fname))
        if os.path.exists(fullpath):
            self.__error(_("WARNING: Output file already exists!\n"
                    "WARNING: It will be overwritten:\n   %(name)s") % \
                    {'name' : fullpath})
            answer = None
            while not answer:
                answer = raw_input(_('OK to overwrite? (yes/no) ') \
                                    .encode(sys.getfilesystemencoding()))
            if answer.upper() in ('Y', 'YES', _('YES').upper()):
                self.__error( _("Will overwrite the existing file: %s") 
                                % fullpath)
            else:
                sys.exit(0)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period, 
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_export_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True
                
        if plugin_found:
            self.exports.append((fullpath, family_tree_format))
        else:
            self.__error(_("ERROR: Unrecognized format for export file %s") 
                            % fname)
            sys.exit(0)
Пример #15
0
def run_report(db, name, **options_str_dict):
    """
    Given a database, run a given report.

    db is a Db database

    name is the name of a report

    options_str_dict is the same kind of options
    given at the command line. For example:
    
    >>> run_report(db, "ancestor_report", off="txt",
                   of="ancestor-007.txt", pid="I37")

    returns CommandLineReport (clr) if successfully runs the report,
    None otherwise.

    You can see:
       options and values used in  clr.option_class.options_dict
       filename in clr.option_class.get_output()
    """
    dbstate = DbState.DbState()
    climanager = CLIManager(dbstate, False)  # don't load db
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    cl_list = pmgr.get_reg_reports()
    clr = None
    for pdata in cl_list:
        if name == pdata.id:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                #import of plugin failed
                return clr
            category = pdata.category
            report_class = getattr(mod, pdata.reportclass)
            options_class = getattr(mod, pdata.optionclass)
            if category in (CATEGORY_BOOK, CATEGORY_CODE):
                options_class(db, name, category, options_str_dict)
            else:
                clr = cl_report(db, name, category, report_class,
                                options_class, options_str_dict)
                return clr
    return clr
Пример #16
0
    def __init__(self,
                 database,
                 name,
                 category,
                 option_class,
                 options_str_dict,
                 noopt=False):

        pmgr = BasePluginManager.get_instance()
        self.__textdoc_plugins = []
        self.__drawdoc_plugins = []
        self.__bookdoc_plugins = []
        for plugin in pmgr.get_docgen_plugins():
            if plugin.get_text_support() and plugin.get_extension():
                self.__textdoc_plugins.append(plugin)
            if plugin.get_draw_support() and plugin.get_extension():
                self.__drawdoc_plugins.append(plugin)
            if plugin.get_text_support() and \
               plugin.get_draw_support() and \
               plugin.get_extension():
                self.__bookdoc_plugins.append(plugin)

        self.database = database
        self.category = category
        self.format = None
        self.option_class = option_class(name, database)
        if category == CATEGORY_GRAPHVIZ:
            # Need to include GraphViz options
            self.__gvoptions = graphdoc.GVOptions()
            menu = self.option_class.menu
            self.__gvoptions.add_menu_options(menu)
            for name in menu.get_all_option_names():
                if name not in self.option_class.options_dict:
                    self.option_class.options_dict[name] = \
                      menu.get_option_by_name(name).get_value()
        self.option_class.load_previous_values()
        _validate_options(self.option_class, database)
        self.show = options_str_dict.pop('show', None)
        self.options_str_dict = options_str_dict
        self.init_standard_options(noopt)
        self.init_report_options()
        self.parse_options()
        self.show_options()
Пример #17
0
    def cl_action(self, action, options_str):
        """
        Command-line action routine. Try to perform specified action.
        """
        pmgr = BasePluginManager.get_instance()
        if action == "report":
            try:
                options_str_dict = dict( [ tuple(chunk.split('='))
                    for chunk in options_str.split(',') ] )
            except:
                options_str_dict = {}
                print "Ignoring invalid options string."

            name = options_str_dict.pop('name', None)
            _cl_list = pmgr.get_reg_reports(gui=False)
            if name:
                for pdata in _cl_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return 
                        category = pdata.category
                        report_class = eval('mod.' + pdata.reportclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        if category in (CATEGORY_BOOK, CATEGORY_CODE):
                            options_class(self.dbstate.db, name, category, 
                                          options_str_dict)
                        else:
                            cl_report(self.dbstate.db, name, category, 
                                      report_class, options_class,
                                      options_str_dict)
                        return
                # name exists, but is not in the list of valid report names
                msg = "Unknown report name."
            else:
                msg = "Report name not given. Please use -p name=reportname."
            
            print "%s\n Available names are:" % msg
            for pdata in _cl_list:
                # Print cli report name ([item[0]) and GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print "   %s%s- %s" % ( pdata.id, 
                                            " " * (26 - len(pdata.id)),
                                            pdata.name.encode(sys.getfilesystemencoding()))
                else:
                    print "   %s\t- %s" % (pdata.id, pdata.name.encode(sys.getfilesystemencoding()) )

        elif action == "tool":
            try:
                options_str_dict = dict( [ tuple(chunk.split('=')) for
                                           chunk in options_str.split(',') ] )
            except:
                options_str_dict = {}
                print "Ignoring invalid options string."

            name = options_str_dict.pop('name', None)
            _cli_tool_list = pmgr.get_reg_tools(gui=False)
            if name:
                for pdata in _cli_tool_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return 
                        category = pdata.category
                        tool_class = eval('mod.' + pdata.toolclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        Tool.cli_tool(self.dbstate, name, category, tool_class, 
                                      options_class, options_str_dict)
                        return
                msg = "Unknown tool name."
            else:
                msg = "Tool name not given. Please use -p name=toolname."
            
            print "%s\n Available names are:" % msg
            for pdata in _cli_tool_list:
                # Print cli report name ([item[0]) and GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print "   %s%s- %s" % ( pdata.id, 
                                            " " * (26 - len(pdata.id)),
                                            pdata.name.encode(sys.getfilesystemencoding()))
                else:
                    print "   %s\t- %s" % (pdata.id, pdata.name.encode(sys.getfilesystemencoding()))
        else:
            print "Unknown action: %s." % action
            sys.exit(0)
Пример #18
0
    def cl_action(self, action, options_str):
        """
        Command-line action routine. Try to perform specified action.
        """
        pmgr = BasePluginManager.get_instance()
        if action == "report":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print >> sys.stderr, _(
                    "Ignoring invalid options string.").encode(
                        sys.getfilesystemencoding())

            name = options_str_dict.pop('name', None)
            _cl_list = pmgr.get_reg_reports(gui=False)
            if name:
                for pdata in _cl_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        report_class = eval('mod.' + pdata.reportclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        if category in (CATEGORY_BOOK, CATEGORY_CODE):
                            options_class(self.dbstate.db, name, category,
                                          options_str_dict)
                        else:
                            cl_report(self.dbstate.db, name, category,
                                      report_class, options_class,
                                      options_str_dict)
                        return
                # name exists, but is not in the list of valid report names
                msg = _("Unknown report name.")
            else:
                msg = _("Report name not given. "
                        "Please use one of %(donottranslate)s=reportname") % \
                        {'donottranslate' : '[-p|--options] name'}

            print >> sys.stderr, (_("%s\n Available names are:") % msg).encode(
                sys.getfilesystemencoding())
            for pdata in sorted(_cl_list, key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print >> sys.stderr, \
                        "   %s%s- %s" % ( pdata.id, " " * (26 - len(pdata.id)),
                                 pdata.name.encode(sys.getfilesystemencoding()))
                else:
                    print >> sys.stderr, "   %s\t- %s" % (
                        pdata.id, pdata.name.encode(
                            sys.getfilesystemencoding()))

        elif action == "tool":
            from gui.plug import tool
            try:
                options_str_dict = dict([
                    tuple(chunk.split('=')) for chunk in options_str.split(',')
                ])
            except:
                options_str_dict = {}
                print >> sys.stderr, _(
                    "Ignoring invalid options string.").encode(
                        sys.getfilesystemencoding())

            name = options_str_dict.pop('name', None)
            _cli_tool_list = pmgr.get_reg_tools(gui=False)
            if name:
                for pdata in _cli_tool_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        tool_class = eval('mod.' + pdata.toolclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        tool.cli_tool(self.dbstate, name, category, tool_class,
                                      options_class, options_str_dict)
                        return
                msg = _("Unknown tool name.")
            else:
                msg = _("Tool name not given. "
                        "Please use one of %(donottranslate)s=toolname.") % \
                        {'donottranslate' : '[-p|--options] name'}

            print >> sys.stderr, _("%s\n Available names are:") % msg
            for pdata in sorted(_cli_tool_list,
                                key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print >> sys.stderr, \
                        "   %s%s- %s" % ( pdata.id, " " * (26 - len(pdata.id)),
                                 pdata.name.encode(sys.getfilesystemencoding()))
                else:
                    print >> sys.stderr, "   %s\t- %s" % (
                        pdata.id, pdata.name.encode(
                            sys.getfilesystemencoding()))
        else:
            print >> sys.stderr, _("Unknown action: %s.") % action
            sys.exit(0)
Пример #19
0
    def cl_action(self, action, options_str):
        """
        Command-line action routine. Try to perform specified action.
        """
        pmgr = BasePluginManager.get_instance()
        if action == "report":
            try:
                options_str_dict = dict([
                    tuple(chunk.split('=')) for chunk in options_str.split(',')
                ])
            except:
                options_str_dict = {}
                print "Ignoring invalid options string."

            name = options_str_dict.pop('name', None)
            _cl_list = pmgr.get_reg_reports(gui=False)
            if name:
                for pdata in _cl_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        report_class = eval('mod.' + pdata.reportclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        if category in (CATEGORY_BOOK, CATEGORY_CODE):
                            options_class(self.dbstate.db, name, category,
                                          options_str_dict)
                        else:
                            cl_report(self.dbstate.db, name, category,
                                      report_class, options_class,
                                      options_str_dict)
                        return
                # name exists, but is not in the list of valid report names
                msg = "Unknown report name."
            else:
                msg = "Report name not given. Please use -p name=reportname."

            print "%s\n Available names are:" % msg
            for pdata in _cl_list:
                # Print cli report name ([item[0]) and GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print "   %s%s- %s" % (pdata.id, " " *
                                           (26 - len(pdata.id)),
                                           pdata.name.encode(
                                               sys.getfilesystemencoding()))
                else:
                    print "   %s\t- %s" % (pdata.id,
                                           pdata.name.encode(
                                               sys.getfilesystemencoding()))

        elif action == "tool":
            try:
                options_str_dict = dict([
                    tuple(chunk.split('=')) for chunk in options_str.split(',')
                ])
            except:
                options_str_dict = {}
                print "Ignoring invalid options string."

            name = options_str_dict.pop('name', None)
            _cli_tool_list = pmgr.get_reg_tools(gui=False)
            if name:
                for pdata in _cli_tool_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        tool_class = eval('mod.' + pdata.toolclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        Tool.cli_tool(self.dbstate, name, category, tool_class,
                                      options_class, options_str_dict)
                        return
                msg = "Unknown tool name."
            else:
                msg = "Tool name not given. Please use -p name=toolname."

            print "%s\n Available names are:" % msg
            for pdata in _cli_tool_list:
                # Print cli report name ([item[0]) and GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print "   %s%s- %s" % (pdata.id, " " *
                                           (26 - len(pdata.id)),
                                           pdata.name.encode(
                                               sys.getfilesystemencoding()))
                else:
                    print "   %s\t- %s" % (pdata.id,
                                           pdata.name.encode(
                                               sys.getfilesystemencoding()))
        else:
            print "Unknown action: %s." % action
            sys.exit(0)
Пример #20
0
# Standard Python modules
#
#-------------------------------------------------------------------------
from xml.sax import make_parser, SAXParseException
import os
import sys

#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from Filters._FilterParser import FilterParser
from gen.plug import BasePluginManager

PLUGMAN = BasePluginManager.get_instance()
#-------------------------------------------------------------------------
#
# FilterList
#
#-------------------------------------------------------------------------
class FilterList(object):
    """
    Container class for managing the generic filters.
    It stores, saves, and loads the filters.
    """
    
    def __init__(self, file):
        self.filter_namespaces = {}
        self.file = os.path.expanduser(file)
        self._cached = {}
Пример #21
0
def available_updates():
    whattypes = config.get('behavior.check-for-update-types')
    if sys.version_info[0] < 3:
        from urllib2 import urlopen
    else:
        from urllib.request import urlopen
    LOG.debug("Checking for updated addons...")
    langs = []
    lang = locale.getlocale()[0]  # not None
    if lang:
        langs.append(lang)
        if "_" in lang:
            lang, variation = lang.split("_", 1)
            langs.append(lang)
    langs.append("en")
    # now we have a list of languages to try:
    fp = None
    for lang in langs:
        URL = ("%s/listings/addons-%s.txt" %
               (config.get("behavior.addons-url"), lang))
        LOG.debug("   trying: %s" % URL)
        try:
            fp = urlopen(URL, timeout=10)  # seconds
        except:
            try:
                URL = ("%s/listings/addons-%s.txt" %
                       (config.get("behavior.addons-url"), lang[:2]))
                fp = urlopen(URL, timeout=10)
            except Exception as err:  # some error
                LOG.warning(
                    "Failed to open addon metadata for {lang} {url}: {err}".
                    format(lang=lang, url=URL, err=err))
                fp = None
        if fp and fp.getcode() == 200:  # ok
            break

    pmgr = BasePluginManager.get_instance()
    addon_update_list = []
    if fp and fp.getcode() == 200:
        lines = list(fp.readlines())
        count = 0
        for line in lines:
            line = line.decode('utf-8')
            try:
                plugin_dict = safe_eval(line)
                if type(plugin_dict) != type({}):
                    raise TypeError("Line with addon metadata is not "
                                    "a dictionary")
            except:
                LOG.warning("Skipped a line in the addon listing: " +
                            str(line))
                continue
            id = plugin_dict["i"]
            plugin = pmgr.get_plugin(id)
            if plugin:
                LOG.debug("Comparing %s > %s" %
                          (version_str_to_tup(plugin_dict["v"], 3),
                           version_str_to_tup(plugin.version, 3)))
                if (version_str_to_tup(plugin_dict["v"], 3) >
                        version_str_to_tup(plugin.version, 3)):
                    LOG.debug("   Downloading '%s'..." % plugin_dict["z"])
                    if "update" in whattypes:
                        if (not config.get(
                                'behavior.do-not-show-previously-seen-updates')
                                or plugin_dict["i"] not in config.get(
                                    'behavior.previously-seen-updates')):
                            addon_update_list.append(
                                (_("Updated"), "%s/download/%s" %
                                 (config.get("behavior.addons-url"),
                                  plugin_dict["z"]), plugin_dict))
                else:
                    LOG.debug("   '%s' is ok" % plugin_dict["n"])
            else:
                LOG.debug("   '%s' is not installed" % plugin_dict["n"])
                if "new" in whattypes:
                    if (not config.get(
                            'behavior.do-not-show-previously-seen-updates')
                            or plugin_dict["i"] not in config.get(
                                'behavior.previously-seen-updates')):
                        addon_update_list.append(
                            (_("New"), "%s/download/%s" %
                             (config.get("behavior.addons-url"),
                              plugin_dict["z"]), plugin_dict))
        config.set("behavior.last-check-for-updates",
                   datetime.date.today().strftime("%Y/%m/%d"))
        count += 1
        if fp:
            fp.close()
    else:
        LOG.debug("Checking Addons Failed")
    LOG.debug("Done checking!")

    return addon_update_list