Beispiel #1
0
    def __init__(self, name, include_private=True, include_living=True):
        """Initialize the database object for family tree `name`.

        This will raise if the database backend is not `sqlite`.
        The constructor does not open/lock the database yet.
        
        Parameters:

        - `include_private`: include records marked as private. Default True
        - `include_living`: include living people. Default True
        """
        self.name = name
        self.include_private = include_private
        self.include_living = include_living
        self.dbstate = DbState()
        self.dbman = CLIDbManager(self.dbstate)
        self.user = User()
        self.smgr = CLIManager(self.dbstate, True, self.user)
        self.path = self.dbman.get_family_tree_path(name)
        if not self.path:
            raise ValueError(
                "Family tree {} not found. Known trees: {}".format(
                    name, self.dbman.family_tree_list()))
        self.db_backend = self.get_dbid()
        if self.db_backend not in ALLOWED_DB_BACKENDS:
            raise ValueError(
                "Database backend '{}' of tree '{}' not supported.".format(
                    self.db_backend, name))
Beispiel #2
0
 def test_dialog(self):
     """
     Tests report dialog integration
     """
     uistate = Familychroniclestest.__mock_uistate(TEST_PERSON_ID)
     dbstate = DbState()
     dbstate.change_database_noclose(self.db)
     TextReportDialog(dbstate, uistate, FamilyChroniclesOptions, "Familiy Chronicles", None)
Beispiel #3
0
    def test_mediapath(self):
        """
        Test media path variables.
        """

        # Create database
        dbstate = DbState()
        db = dbstate.make_database("bsddb")
        path = get_empty_tempdir("utils_file_test")
        db.write_version(path)
        db.load(path)
        dbstate.change_database(db)

        # Test without db.mediapath set
        self.assertEqual(media_path(db), os.path.normcase(os.path.normpath(os.path.abspath(USER_HOME))))
        self.assertTrue(os.path.exists(media_path(db)))

        # Test with absolute db.mediapath
        db.set_mediapath(os.path.abspath(USER_HOME) + "/test_abs")
        self.assertEqual(media_path(db), os.path.normcase(os.path.normpath(os.path.abspath(USER_HOME + "/test_abs"))))

        # Test with relative db.mediapath
        db.set_mediapath("test_rel")
        self.assertEqual(
            media_path(db), os.path.normcase(os.path.normpath(os.path.abspath(TEMP_DIR + "/utils_file_test/test_rel")))
        )

        # Test with environment variable
        db.set_mediapath("/test/{VERSION}/test_var")
        self.assertEqual(
            media_path(db), os.path.normcase(os.path.normpath(os.path.abspath("/test/" + VERSION + "/test_var")))
        )
        db.set_mediapath("{USER_PLUGINS}/test_var")
        self.assertEqual(
            media_path(db), os.path.normcase(os.path.normpath(os.path.abspath(USER_PLUGINS + "/test_var")))
        )
        db.set_mediapath("{VERSION}/test_var")
        self.assertEqual(
            media_path(db),
            os.path.normcase(os.path.normpath(os.path.abspath(TEMP_DIR + "/utils_file_test/" + VERSION + "/test_var"))),
        )

        # Test with $GRAMPSHOME environment variable not set
        old_env = os.environ.copy()
        if "GRAMPSHOME" in os.environ:
            del os.environ["GRAMPSHOME"]
        db.set_mediapath("{GRAMPSHOME}/test_var")
        self.assertEqual(media_path(db), os.path.normcase(os.path.normpath(os.path.abspath(USER_HOME + "/test_var"))))

        # Test with $GRAMPSHOME environment variable set
        os.environ["GRAMPSHOME"] = "/this/is/a/test"
        db.set_mediapath("{GRAMPSHOME}/test_var")
        self.assertEqual(
            media_path(db), os.path.normcase(os.path.normpath(os.path.abspath("/this/is/a/test/test_var")))
        )

        #  Restore environment
        os.environ = old_env
Beispiel #4
0
 def show_preview_data(self, widget):
     from gramps.gen.dbstate import DbState
     from ..quick import run_quick_report_by_name
     if widget.proxy_name == "unfiltered":
         dbstate = self.dbstate
     else:
         dbstate = DbState()
         dbstate.db = self.proxy_dbase[widget.proxy_name]
         dbstate.open = True
     run_quick_report_by_name(dbstate, self.uistate, 'filterbyname', 'all')
Beispiel #5
0
    def setUp(self):
        def dummy_callback(dummy):
            pass

        self.dbstate = DbState()
        self.dbman = CLIDbManager(self.dbstate)
        dirpath, name = self.dbman.create_new_db_cli("Test: bsddb",
                                                     dbid="bsddb")
        self._db = self.dbstate.make_database("bsddb")
        self._db.load(dirpath, None)
 def test_editreference(self):
     dbstate = DbState()
     dbstate.db = self.db
     source = Place() 
     source.gramps_id = "P0001"
     self.db.place_map[source.handle] = source
     editor = MockEditReference(dbstate, uistate=None, track=[], 
                                source=source, source_ref=None, update=None)
     with patch('gramps.gui.editors.editreference.ErrorDialog') as MockED:
         editor.check_for_duplicate_id("Place")
         self.assertTrue(MockED.called)
Beispiel #7
0
 def show_preview_data(self, widget):
     from gramps.gen.dbstate import DbState
     from ..quick import run_quick_report_by_name
     if widget.proxy_name == "unfiltered":
         dbstate = self.dbstate
     else:
         dbstate = DbState()
         dbstate.db = self.proxy_dbase[widget.proxy_name]
         dbstate.open = True
     run_quick_report_by_name(dbstate,
                              self.uistate,
                              'filterbyname',
                              'all')
Beispiel #8
0
 def test_editreference(self):
     dbstate = DbState()
     dbstate.db = self.db
     source = Place()
     source.gramps_id = "P0001"
     self.db.place_map[source.handle] = source
     editor = MockEditReference(dbstate,
                                uistate=None,
                                track=[],
                                source=source,
                                source_ref=None,
                                update=None)
     with patch('gramps.gui.editors.editreference.ErrorDialog') as MockED:
         editor.check_for_duplicate_id("Place")
         self.assertTrue(MockED.called)
Beispiel #9
0
 def write(self) -> None:
     """Write the example DB to a SQLite DB and change the DB path."""
     self.tmp_dbdir = tempfile.mkdtemp()
     self.old_path = getconfig("database.path")
     setconfig("database.path", self.tmp_dbdir)
     dbman = CLIDbManager(DbState())
     dbman.import_new_db(self.path, User())
Beispiel #10
0
    def __init__(self, argparser):
        from gramps.gen.dbstate import DbState
        from guiQML.viewmanager import ViewManager
        from gramps.cli.arghandler import ArgHandler

        from PySide import QtGui
        self.app = QtGui.QApplication(sys.argv)
        dbstate = DbState()
        self.vm = ViewManager(dbstate)

        #act based on the given arguments
        ah = ArgHandler(dbstate, argparser, self.vm, self.argerrorfunc,
                        gui=True)
        ah.handle_args_gui()
        if ah.open or ah.imp_db_path:
            # if we opened or imported something, only show the interface
            self.vm.post_init_interface()
        elif config.get('paths.recent-file') and config.get('behavior.autoload'):
            # if we need to autoload last seen file, do so
            filename = config.get('paths.recent-file')
            if os.path.isdir(filename) and \
                    os.path.isfile(os.path.join(filename, "name.txt")) and \
                    ah.check_db(filename):
                self.vm.open_activate(filename)
                self.vm.post_init_interface()
            else:
                self.vm.post_init_interface()
        else:
            # open without fam tree loaded
            self.vm.post_init_interface()
        
        #start the QT loop
        self.app.exec_()
Beispiel #11
0
def export_file(db, filename, user):
    """
    Export the db to a file (such as a GEDCOM file).

    >>> export_file(DbDjango(), "/home/user/Untitled_1.ged", User())
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False,
                            user=user)  # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    (name, ext) = os.path.splitext(os.path.basename(filename))
    format = ext[1:].lower()
    export_list = pmgr.get_reg_exporters()
    for pdata in export_list:
        if format == pdata.extension:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                for item in pmgr.get_fail_list():
                    name, error_tuple, pdata = item
                    etype, exception, traceback = error_tuple
                    print("ERROR:", name, exception)
                return False
            export_function = getattr(mod, pdata.export_function)
            export_function(db, filename, user)
            return True
    return False
Beispiel #12
0
def import_file(db, filename, user):
    """
    Import a file (such as a GEDCOM file) into the given db.

    >>> import_file(DbDjango(), "/home/user/Untitled_1.ged", User())
    """
    from .grampsdb.models import Person
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False,
                            user=user)  # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    (name, ext) = os.path.splitext(os.path.basename(filename))
    format = ext[1:].lower()
    import_list = pmgr.get_reg_importers()
    for pdata in import_list:
        if format == pdata.extension:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                for item in pmgr.get_fail_list():
                    name, error_tuple, pdata = item
                    # (filename, (exception-type, exception, traceback), pdata)
                    etype, exception, traceback = error_tuple
                    print("ERROR:", name, exception)
                return False
            import_function = getattr(mod, pdata.import_function)
            db.prepare_import()
            retval = import_function(db, filename, user)
            db.commit_import()
            return retval
    return False
Beispiel #13
0
 def setUpClass(cls):
     cls.name = "Test Web API"
     cls.dbman = CLIDbManager(DbState())
     _, _name = cls.dbman.create_new_db_cli(cls.name, dbid="sqlite")
     with patch.dict("os.environ", {ENV_CONFIG_FILE: TEST_CONFIG}):
         cls.app = create_app()
     cls.app.config["TESTING"] = True
     cls.client = cls.app.test_client()
Beispiel #14
0
 def __init__(self, user=None, dbstate=None):
     ## Setup:
     from gramps.cli.clidbman import CLIDbManager
     self.dbstate = dbstate or DbState()
     #we need a manager for the CLI session
     self.user = user or User()
     self.climanager = CLIManager(self.dbstate, setloader=True, user=self.user)
     self.clidbmanager = CLIDbManager(self.dbstate)
Beispiel #15
0
 def test_editreference(self):
     dbstate = DbState()
     db = make_database("bsddb")
     path = "/tmp/edit_ref_test"
     try:
         os.mkdir(path)
     except:
         pass
     db.load(path)
     dbstate.change_database(db)
     source = Place()
     source.gramps_id = "P0001"
     dbstate.db.place_map[source.handle] = source.serialize()
     editor = MockEditReference(dbstate, uistate=None, track=[],
                                source=source, source_ref=None, update=None)
     with patch('gramps.gui.editors.editreference.ErrorDialog') as MockED:
         editor.check_for_duplicate_id("Place")
         self.assertTrue(MockED.called)
Beispiel #16
0
    def setUp(self):
        def dummy_callback(dummy):
            pass

        self.dbstate = DbState()
        self.dbman = CLIDbManager(self.dbstate)
        dirpath, name = self.dbman.create_new_db_cli("Test: bsddb", dbid="bsddb")
        self._db = self.dbstate.make_database("bsddb")
        self._db.load(dirpath, None)
Beispiel #17
0
    def __init__(self, argparser):
        from gramps.gen.dbstate import DbState
        from . import viewmanager
        from .viewmanager import ViewManager
        from gramps.cli.arghandler import ArgHandler
        from .tipofday import TipOfDay
        from .dialog import WarningDialog
        import gettext

        _display_welcome_message()
        register_stock_icons()

        if lin() and glocale.lang != 'C' and not gettext.find(GTK_GETTEXT_DOMAIN):
            LOG.warn("GTK translations missing, GUI will be broken, especially for RTL languages!")
            # Note: the warning dialog below will likely have wrong stock icons!
            # Translators: the current language will be the one you translate into.
            WarningDialog(
               _("Gramps detected an incomplete GTK installation"),
               _("GTK translations for the current language (%(language)s) "
                 "are missing.\n%(bold_start)sGramps%(bold_end)s will "
                 "proceed nevertheless.\nThe GUI will likely be broken "
                 "as a result, especially for RTL languages!\n\n"
                 "See the Gramps README documentation for installation "
                 "prerequisites,\ntypically located in "
                 "/usr/share/doc/gramps.\n") % {
                     'language'   : glocale.lang ,
                     'bold_start' : '<b>' ,
                     'bold_end'   : '</b>' } )

        dbstate = DbState()
        self.vm = ViewManager(dbstate, 
                config.get("interface.view-categories"))
        self.vm.init_interface()

        #act based on the given arguments
        ah = ArgHandler(dbstate, argparser, self.vm, self.argerrorfunc,
                        gui=True)
        ah.handle_args_gui()
        if ah.open or ah.imp_db_path:
            # if we opened or imported something, only show the interface
            self.vm.post_init_interface(show_manager=False)
        elif config.get('paths.recent-file') and config.get('behavior.autoload'):
            # if we need to autoload last seen file, do so
            filename = config.get('paths.recent-file')
            if os.path.isdir(filename) and \
                    os.path.isfile(os.path.join(filename, "name.txt")) and \
                    ah.check_db(filename):
                self.vm.post_init_interface(show_manager=False)
                self.vm.open_activate(filename)
            else:
                self.vm.post_init_interface()
        else:
            # open without fam tree loaded
            self.vm.post_init_interface()

        if config.get('behavior.use-tips'):
            TipOfDay(self.vm.uistate)
 def setUpClass(cls):
     # print("doing setup with", cls.param)
     set_det_id(True)  # handles must be deterministic for this test
     cls.dbstate = DbState()
     cls.dbman = CLIDbManager(cls.dbstate)
     dirpath, _name = cls.dbman.create_new_db_cli("Test: %s" % cls.param,
                                                  dbid=cls.param)
     cls.db = make_database(cls.param)
     cls.db.load(dirpath, None)
Beispiel #19
0
    def setUp(self):
        def dummy_callback(dummy):
            pass

        self._tmpdir = tempfile.mkdtemp()

        self._db = DbBsddb()
        dbman = CLIDbManager(DbState())
        self._filename, title = dbman.create_new_db_cli(title="Test")
        self._db.load(self._filename, dummy_callback, "w")
Beispiel #20
0
 def test_editreference(self):
     dbstate = DbState()
     db = dbstate.make_database("bsddb")
     path = "/tmp/edit_ref_test"
     try:
         os.mkdir(path)
     except:
         pass
     db.write_version(path)
     db.load(path)
     dbstate.change_database(db)
     source = Place()
     source.gramps_id = "P0001"
     dbstate.db.place_map[source.handle] = source.serialize()
     editor = MockEditReference(dbstate, uistate=None, track=[],
                                source=source, source_ref=None, update=None)
     with patch('gramps.gui.editors.editreference.ErrorDialog') as MockED:
         editor.check_for_duplicate_id("Place")
         self.assertTrue(MockED.called)
Beispiel #21
0
 def _get_path(self) -> str:
     """Get the path of the family tree database."""
     dbstate = DbState()  # dbstate instance used only for this method
     dbman = CLIDbManager(dbstate)
     path = dbman.get_family_tree_path(self.name)
     if path is None:
         raise ValueError(
             "Database path for family tree '{}' not found in databse directory {}"
             .format(self.name, config.get("database.path")))
     return path
Beispiel #22
0
 def setUpClass(cls):
     cls.name = "Test Web API"
     cls.dbman = CLIDbManager(DbState())
     _, _name = cls.dbman.create_new_db_cli(cls.name, dbid="sqlite")
     with patch.dict("os.environ", {ENV_CONFIG_FILE: TEST_AUTH_CONFIG}):
         cls.app = create_app()
     cls.app.config["TESTING"] = True
     cls.client = cls.app.test_client()
     sqlauth = cls.app.config["AUTH_PROVIDER"]
     sqlauth.create_table()
     sqlauth.add_user(name="user", password="******")
Beispiel #23
0
 def setUp(self):
     from gramps.cli.clidbman import CLIDbManager
     from gramps.gen.config import set as setconfig, get as getconfig
     from gramps.gen.dbstate import DbState
     self.newpath = os.path.join(os.path.dirname(__file__),
                                 '\u0393\u03c1\u03b1\u03bc\u03c3\u03c0')
     self.newtitle = 'Gr\u00e4mps T\u00e9st'
     os.makedirs(self.newpath)
     self.old_path = getconfig('database.path')
     setconfig('database.path', self.newpath)
     self.cli = CLIDbManager(DbState())
 def setUp(self):
     self.name = "Test Web API"
     self.dbman = CLIDbManager(DbState())
     _, _name = self.dbman.create_new_db_cli(self.name, dbid="sqlite")
     with patch.dict("os.environ", {ENV_CONFIG_FILE: TEST_AUTH_CONFIG}):
         self.app = create_app()
     self.app.config["TESTING"] = True
     self.client = self.app.test_client()
     sqlauth = self.app.config["AUTH_PROVIDER"]
     sqlauth.create_table()
     self.ctx = self.app.test_request_context()
     self.ctx.push()
Beispiel #25
0
    def __init__(self, argparser):
        from gramps.gen.dbstate import DbState
        from . import viewmanager
        from .viewmanager import ViewManager
        from gramps.cli.arghandler import ArgHandler
        from .tipofday import TipOfDay
        import gettext

        # Append image directory to the theme search path
        theme = Gtk.IconTheme.get_default()
        theme.append_search_path(IMAGE_DIR)

        dbstate = DbState()
        self._vm = ViewManager(dbstate,
                               config.get("interface.view-categories"))

        if (lin() and glocale.lang != 'C'
                and not gettext.find(GTK_GETTEXT_DOMAIN)):
            _display_gtk_gettext_message(parent=self._vm.window)

        #_display_welcome_message(parent=self._vm.window)

        _display_translator_message(parent=self._vm.window)

        self._vm.init_interface()

        #act based on the given arguments
        arg_h = ArgHandler(dbstate,
                           argparser,
                           self._vm,
                           self.argerrorfunc,
                           gui=True)
        arg_h.handle_args_gui()
        if arg_h.open or arg_h.imp_db_path:
            # if we opened or imported something, only show the interface
            self._vm.post_init_interface(show_manager=False)
        elif (config.get('paths.recent-file')
              and config.get('behavior.autoload')):
            # if we need to autoload last seen file, do so
            filename = config.get('paths.recent-file')
            if (os.path.isdir(filename)
                    and os.path.isfile(os.path.join(filename, "name.txt"))
                    and arg_h.check_db(filename)):
                self._vm.post_init_interface(show_manager=False)
                self._vm.open_activate(filename)
            else:
                self._vm.post_init_interface()
        else:
            # open without fam tree loaded
            self._vm.post_init_interface()

        if config.get('behavior.use-tips'):
            TipOfDay(self._vm.uistate)
Beispiel #26
0
    def get_db(self, force_unlock: bool = False) -> DbState:
        """Open the database and return a dbstate instance.

        If `force_unlock` is `True`, will break an existing lock (use with care!).
        """
        dbstate = DbState()
        user = User()
        smgr = CLIManager(dbstate, True, user)
        if force_unlock:
            self.break_lock()
        smgr.open_activate(self.path)
        return dbstate
Beispiel #27
0
 def __init__(self, name: str = None) -> None:
     """Prepare and import the example DB."""
     ExampleDbBase.__init__(self)
     self.db_path = os.path.join(os.environ["GRAMPSHOME"], "gramps",
                                 "grampsdb")
     os.makedirs(self.db_path, exist_ok=True)
     setconfig("database.path", self.db_path)
     dbstate = DbState()
     dbman = CLIDbManager(dbstate)
     user = User()
     smgr = CLIManager(dbstate, True, user)
     smgr.do_reg_plugins(dbstate, uistate=None)
     self.path, self.name = dbman.import_new_db(self.path, User())
     WebDbManager.__init__(self, self.name)
 def setUpClass(cls):
     cls.name = "Test Web API"
     cls.dbman = CLIDbManager(DbState())
     cls.dbman.create_new_db_cli(cls.name, dbid="sqlite")
     with patch.dict("os.environ", {ENV_CONFIG_FILE: TEST_AUTH_CONFIG}):
         cls.app = create_app()
     cls.app.config["TESTING"] = True
     cls.media_base_dir = tempfile.mkdtemp()
     cls.app.config["MEDIA_BASE_DIR"] = cls.media_base_dir
     cls.client = cls.app.test_client()
     sqlauth = cls.app.config["AUTH_PROVIDER"]
     sqlauth.create_table()
     sqlauth.add_user(name="user", password="******", role=ROLE_GUEST)
     sqlauth.add_user(name="admin", password="******", role=ROLE_OWNER)
 def test_editreference(self):
     dbstate = DbState()
     db = make_database("sqlite")
     path = "/tmp/edit_ref_test"
     try:
         os.mkdir(path)
     except:
         pass
     db.load(path)
     dbstate.change_database(db)
     source = Place()
     source.gramps_id = "P0001"
     with DbTxn("test place", dbstate.db) as trans:
         dbstate.db.add_place(source, trans)
     editor = MockEditReference(dbstate,
                                uistate=None,
                                track=[],
                                source=source,
                                source_ref=None,
                                update=None)
     with patch('gramps.gui.editors.editreference.ErrorDialog') as MockED:
         editor.check_for_duplicate_id("Place")
         self.assertTrue(MockED.called)
Beispiel #30
0
    def get_db(self, lock: bool = False, force_unlock: bool = False) -> DbState:
        """Open the database and return a dbstate instance.

        If `lock` is `False`, will not write a lock file (use with care!).
        If `force_unlock` is `True`, will break an existing lock (use with care!).
        """
        dbstate = DbState()
        user = User()
        smgr = WebDbSessionManager(dbstate, user)
        smgr.do_reg_plugins(dbstate, uistate=None)
        if force_unlock:
            self.break_lock()
        mode = DBMODE_W if lock else DBMODE_R
        smgr.open_activate(self.path, mode=mode)
        return dbstate
 def setUpClass(cls):
     cls.name = "Test Web API"
     cls.dbman = CLIDbManager(DbState())
     cls.dbman.create_new_db_cli(cls.name, dbid="sqlite")
     with patch.dict("os.environ", {ENV_CONFIG_FILE: TEST_AUTH_CONFIG}):
         cls.app = create_app()
     cls.app.config["TESTING"] = True
     cls.client = cls.app.test_client()
     sqlauth = cls.app.config["AUTH_PROVIDER"]
     sqlauth.create_table()
     sqlauth.add_user(name="user", password="******", role=ROLE_GUEST)
     sqlauth.add_user(name="contributor", password="******", role=ROLE_CONTRIBUTOR)
     sqlauth.add_user(name="admin", password="******", role=ROLE_OWNER)
     sqlauth.add_user(name="editor", password="******", role=ROLE_EDITOR)
     sqlauth.add_user(name="member", password="******", role=ROLE_MEMBER)
Beispiel #32
0
 def test_example_db_sqlite(self):
     """Test the SQLite example DB."""
     test_grampshome = tempfile.mkdtemp()
     os.environ["GRAMPSHOME"] = test_grampshome
     db = ExampleDbSQLite()
     self.assertEqual(getconfig("database.path"), db.db_path)
     dbman = CLIDbManager(DbState())
     db_info = dbman.current_names
     # there is only one DB here
     self.assertEqual(len(db_info), 1)
     # DB name
     self.assertEqual(db_info[0][0], "example")
     # DB path
     self.assertEqual(os.path.dirname(db_info[0][1]), db.db_path)
     # DB cleanup
     shutil.rmtree(test_grampshome)
     self.assertTrue(not os.path.exists(test_grampshome))
Beispiel #33
0
    def setUpClass(cls):
        cls.name = "Test Web API"
        cls.dbman = CLIDbManager(DbState())
        _, _name = cls.dbman.create_new_db_cli(cls.name, dbid="sqlite")
        cls.config_file = tempfile.NamedTemporaryFile(delete=False)
        cls.user_db = tempfile.NamedTemporaryFile(delete=False)
        config = """TREE="Test Web API"
SECRET_KEY="C2eAhXGrXVe-iljXTjnp4paeRT-m68pq"
USER_DB_URI="sqlite:///{}"
""".format(cls.user_db.name)
        with open(cls.config_file.name, "w") as f:
            f.write(config)
        with patch.dict("os.environ", {ENV_CONFIG_FILE: cls.config_file.name}):
            cls.app = create_app()
        cls.app.config["TESTING"] = True
        cls.client = cls.app.test_client()
        cls.runner = CliRunner()
Beispiel #34
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()
    climanager = CLIManager(dbstate, setloader=False, user=User()) # 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
Beispiel #35
0
def get_plugin_options(db, pid):
    """
    Get the default options and help for this plugin.
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False,
                            user=GUser())  # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    pdata = pmgr.get_plugin(pid)
    if hasattr(pdata, "optionclass") and pdata.optionclass:
        mod = pmgr.load_plugin(pdata)
        optionclass = eval("mod." + pdata.optionclass)
        optioninstance = optionclass("Name", db)
        optioninstance.load_previous_values()
        return optioninstance.options_dict, optioninstance.options_help
    else:
        return {}, {}
Beispiel #36
0
    if commit:
        db.transaction_commit(tran)
        tran = None

def print_db_content(db):
    for h in db.get_person_handles():
        print("DB contains: person %s" % h)
    for h in db.get_source_handles():
        print("DB contains: source %s" % h)

tmpdir = tempfile.mkdtemp()
try:
    filename1 = os.path.join(tmpdir,'test1.grdb')
    filename2 = os.path.join(tmpdir,'test2.grdb')
    print("\nUsing Database file: %s" % filename1)
    dbstate = DbState()
    dbman = CLIDbManager(dbstate)
    dirpath, name = dbman.create_new_db_cli(filename1, dbid="bsddb")
    db = dbstate.make_database("bsddb")
    db.load(dirpath, None)
    print("Add person 1")
    add_person( db,"Anton", "Albers",True,False)
    print("Add source")
    add_source( db,"A short test",True,False)
    print("Add person 2 without commit")
    add_person( db,"Bernd","Beta",False,False)
    print("Add source")
    add_source( db,"A short test",True,False)
    print("Add person 3")
    add_person( db,"Chris","Connor",True,False)
    print_db_content( db)
Beispiel #37
0
class GrampsConnect(Application):
    """
    Main Gramps Connect webapp class
    """
    def __init__(self, options, settings=None):
        self.options = options
        if settings is None:
            settings = self.default_settings()
        if self.options.database is None:
            raise Exception("Need to specify Gramps Family Tree name with --database='NAME'")
        else:
            self.database = DbState().open_database(self.options.database)
        if self.database is None:
            raise Exception("Unable to open database '%s'" % self.options.database)
        self.sitename = self.options.sitename
        super().__init__([
            url(r"/", HomeHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="main"),
            url(r'/login', LoginHandler,
                {
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="login"),
            url(r'/logout', LogoutHandler,
                {
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="logout"),
            url(r'/(.*)/(.*)/delete', DeleteHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
            ),
            url(r'/action/?(.*)', ActionHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="action"),
            url(r'/person/?(.*)', PersonHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="person"),
            url(r'/note/?(.*)', NoteHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="note"),
            url(r'/family/?(.*)', FamilyHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="family"),
            url(r'/citation/?(.*)', CitationHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="citation"),
            url(r'/event/?(.*)', EventHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="event"),
            url(r'/media/?(.*)', MediaHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="media"),
            url(r'/place/?(.*)', PlaceHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="place"),
            url(r'/repository/?(.*)', RepositoryHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="repository"),
            url(r'/source/?(.*)', SourceHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="source"),
            url(r'/tag/?(.*)', TagHandler,
                {
                    "database": self.database,
                    "sitename": self.sitename,
                    "opts" : self.options,
                },
                name="tag"),
            url(r'/imageserver/(.*)', ImageHandler,
                {
                    "database": self.database,
                    "opts" : self.options,
                    "HOMEDIR": self.options.home_dir,
                    "PORT": self.options.port,
                    "HOSTNAME": self.options.hostname,
                    "GET_IMAGE_FN": self.get_image_path_from_handle,
                    "sitename": self.sitename,
                },
                name="imageserver",
            ),
            url(r"/json/", JsonHandler,
                {
                    "database": self.database,
                }
            ),
            url(r"/data/(.*)", StaticFileHandler,
                {
                    'path': self.options.data_dir,
                }),
            url(r"/css/(.*)", StaticFileHandler,
                {
                    'path': os.path.join(gramps.gen.const.DATA_DIR, "css"),
                }),
            url(r"/images/(.*)", StaticFileHandler,
                {
                    'path': os.path.join(gramps.gen.const.DATA_DIR, "images"),
                }),
            url(r"/misc/(.*)", StaticFileHandler,
                {
                    'path': gramps.gen.const.IMAGE_DIR,
                }),
            url(r"/img/(.*)", StaticFileHandler,
                {
                    'path': os.path.join(gramps.gen.const.PLUGINS_DIR, "webstuff", "img"),
                }),
        ], **settings)

    def default_settings(self):
        """
        """
        return {
            "cookie_secret": base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes),
            "login_url":     "/login",
            'template_path': os.path.join(self.options.data_dir, "templates"),
            'debug':         self.options.debug,
            "xsrf_cookies":  self.options.xsrf,
        }

    def get_image_path_from_handle(self, identifier):
        """
        Given an image handle, return the full path/filename.
        """
        media = self.database.get_media_from_handle(identifier)
        if media:
            return media_path_full(self.database, media.get_path())
        return ""
Beispiel #38
0
 def __init__(self, options, settings=None):
     self.options = options
     if settings is None:
         settings = self.default_settings()
     if self.options.database is None:
         raise Exception("Need to specify Gramps Family Tree name with --database='NAME'")
     else:
         self.database = DbState().open_database(self.options.database)
     if self.database is None:
         raise Exception("Unable to open database '%s'" % self.options.database)
     self.sitename = self.options.sitename
     super().__init__([
         url(r"/", HomeHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="main"),
         url(r'/login', LoginHandler,
             {
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="login"),
         url(r'/logout', LogoutHandler,
             {
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="logout"),
         url(r'/(.*)/(.*)/delete', DeleteHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
         ),
         url(r'/action/?(.*)', ActionHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="action"),
         url(r'/person/?(.*)', PersonHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="person"),
         url(r'/note/?(.*)', NoteHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="note"),
         url(r'/family/?(.*)', FamilyHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="family"),
         url(r'/citation/?(.*)', CitationHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="citation"),
         url(r'/event/?(.*)', EventHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="event"),
         url(r'/media/?(.*)', MediaHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="media"),
         url(r'/place/?(.*)', PlaceHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="place"),
         url(r'/repository/?(.*)', RepositoryHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="repository"),
         url(r'/source/?(.*)', SourceHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="source"),
         url(r'/tag/?(.*)', TagHandler,
             {
                 "database": self.database,
                 "sitename": self.sitename,
                 "opts" : self.options,
             },
             name="tag"),
         url(r'/imageserver/(.*)', ImageHandler,
             {
                 "database": self.database,
                 "opts" : self.options,
                 "HOMEDIR": self.options.home_dir,
                 "PORT": self.options.port,
                 "HOSTNAME": self.options.hostname,
                 "GET_IMAGE_FN": self.get_image_path_from_handle,
                 "sitename": self.sitename,
             },
             name="imageserver",
         ),
         url(r"/json/", JsonHandler,
             {
                 "database": self.database,
             }
         ),
         url(r"/data/(.*)", StaticFileHandler,
             {
                 'path': self.options.data_dir,
             }),
         url(r"/css/(.*)", StaticFileHandler,
             {
                 'path': os.path.join(gramps.gen.const.DATA_DIR, "css"),
             }),
         url(r"/images/(.*)", StaticFileHandler,
             {
                 'path': os.path.join(gramps.gen.const.DATA_DIR, "images"),
             }),
         url(r"/misc/(.*)", StaticFileHandler,
             {
                 'path': gramps.gen.const.IMAGE_DIR,
             }),
         url(r"/img/(.*)", StaticFileHandler,
             {
                 'path': os.path.join(gramps.gen.const.PLUGINS_DIR, "webstuff", "img"),
             }),
     ], **settings)
Beispiel #39
0
class GrampsDbBaseTest(unittest.TestCase):
    """Base class for unittest that need to be able to create
    test databases."""

    def setUp(self):
        def dummy_callback(dummy):
            pass

        self.dbstate = DbState()
        self.dbman = CLIDbManager(self.dbstate)
        dirpath, name = self.dbman.create_new_db_cli("Test: bsddb", dbid="bsddb")
        self._db = self.dbstate.make_database("bsddb")
        self._db.load(dirpath, None)

    def tearDown(self):
        self._db.close()
        self.dbman.remove_database("Test: bsddb")

    def _populate_database(self,
                           num_sources = 1,
                           num_persons = 0,
                           num_families = 0,
                           num_events = 0,
                           num_places = 0,
                           num_media_objects = 0,
                           num_links = 1):
        # start with sources
        sources = []
        for i in range(num_sources):
            sources.append(self._add_source())

        # now for each of the other tables. Give each entry a link
        # to num_link sources, sources are chosen on a round robin
        # basis

        for num, add_func in ((num_persons, self._add_person_with_sources),
                              (num_families, self._add_family_with_sources),
                              (num_events, self._add_event_with_sources),
                              (num_places, self._add_place_with_sources),
                              (num_media_objects, self._add_media_object_with_sources)):

            source_idx = 1
            for person_idx in range(num):

                # Get the list of sources to link
                lnk_sources = set()
                for i in range(num_links):
                    lnk_sources.add(sources[source_idx-1])
                    source_idx = (source_idx+1) % len(sources)

                try:
                    add_func(lnk_sources)
                except:
                    print ("person_idx = ", person_idx)
                    print ("lnk_sources = ", repr(lnk_sources))
                    raise

        return

    def _add_source(self,repos=None):
        # Add a Source

        with DbTxn("Add Source and Citation", self._db) as tran:
            source = Source()
            if repos is not None:
                repo_ref = RepoRef()
                repo_ref.set_reference_handle(repos.get_handle())
                source.add_repo_reference(repo_ref)
            self._db.add_source(source, tran)
            self._db.commit_source(source, tran)
            citation = Citation()
            citation.set_reference_handle(source.get_handle())
            self._db.add_citation(citation, tran)
            self._db.commit_citation(citation, tran)

        return citation

    def _add_repository(self):
        # Add a Repository

        with DbTxn("Add Repository", self._db) as tran:
            repos = Repository()
            self._db.add_repository(repos, tran)
            self._db.commit_repository(repos, tran)

        return repos


    def _add_object_with_source(self, citations, object_class, add_method,
                                commit_method):

        object = object_class()

        with DbTxn("Add Object", self._db) as tran:
            for citation in citations:
                object.add_citation(citation.get_handle())
            add_method(object, tran)
            commit_method(object, tran)

        return object

    def _add_person_with_sources(self, citations):

        return self._add_object_with_source(citations,
                                            Person,
                                            self._db.add_person,
                                            self._db.commit_person)

    def _add_family_with_sources(self, citations):

        return self._add_object_with_source(citations,
                                            Family,
                                            self._db.add_family,
                                            self._db.commit_family)

    def _add_event_with_sources(self, citations):

        return self._add_object_with_source(citations,
                                            Event,
                                            self._db.add_event,
                                            self._db.commit_event)

    def _add_place_with_sources(self, citations):

        return self._add_object_with_source(citations,
                                            Place,
                                            self._db.add_place,
                                            self._db.commit_place)

    def _add_media_object_with_sources(self, citations):

        return self._add_object_with_source(citations,
                                            MediaObject,
                                            self._db.add_object,
                                            self._db.commit_media_object)