コード例 #1
0
 def run(self):
     """
     Perform the actual extraction of information.
     """
     menu = self.options.menu
     self.filter = menu.get_option_by_name('filter').get_filter()
     sort_func_num = menu.get_option_by_name('sort_by').get_value()
     self.sort_desc = menu.get_option_by_name('sort_desc').get_value()
     self.fam_events = menu.get_option_by_name('family_events').get_value()
     sort_functions = _get_sort_functions(Sort(self.db))
     self.sort_name = sort_functions[sort_func_num][0]
     self.sort_func = sort_functions[sort_func_num][1]
     self.sort = Sort(self.db)
     with DbTxn(_("Sort event changes"), self.db, batch=True) as trans:
         self.db.disable_signals()
         family_handles = self.sort_person_events(trans)
         if len(family_handles) > 0:
             self.sort_family_events(family_handles, trans)
     self.db.enable_signals()
     self.db.request_rebuild()
コード例 #2
0
ファイル: NoteCleanup.py プロジェクト: uli22/addons-source
 def gentest(self, button):
     """
     Create some test notes.
     """
     with DbTxn(_("Cleanup Test Notes"), self.db) as trans:
         gid = 'N99996'
         text='A note with <a target=new href="'\
             'http://seekingmichigan.org">'\
             'http://seekingmichigan.org</a>.'
         self.add_note(gid, text, trans)
         gid = 'N99997'
         text = 'http://www.google.com'
         self.add_note(gid, text, trans)
         gid = 'N99998'
         text= 'Quick test of <i>italics</i>, <b>bold</b>, <u>underline'\
             '</u>, and <a href="http://www.google.com">Google</a>.'
         self.add_note(gid, text, trans)
         gid = 'N99999'
         text = 'An <??>issue</??> with this note'
         self.add_note(gid, text, trans)
コード例 #3
0
ファイル: tags.py プロジェクト: shalevy1/gramps
    def run(self):
        """
        Run the dialog and return the result.
        """
        self._populate_model()
        while True:
            # the self.top.run() makes Gtk make it modal, so any change to that
            # line would require the ManagedWindow.__init__ to be changed also
            response = self.top.run()
            if response == Gtk.ResponseType.HELP:
                display_help(webpage=WIKI_HELP_PAGE, section=WIKI_HELP_SEC)
            else:
                break

        # Save changed priority values
        if response == Gtk.ResponseType.CLOSE and self.__priorities_changed():
            with DbTxn(_('Change Tag Priority'), self.db) as trans:
                self.__change_tag_priority(trans)
        if response != Gtk.ResponseType.DELETE_EVENT:
            self.close()
コード例 #4
0
    def addPlace(pname, ptype, refPlace=None, plang='fi'):
        place = Place()
        placeName = PlaceName()
        placeName.set_value(pname)
        placeName.set_language(plang)
        place.set_name(placeName)
        #        place.set_change_time(chgtime)
        place.set_type(ptype)
        place.add_tag(tags[ptype])
        if refPlace != None:
            placeRef = PlaceRef()
            placeRef.set_reference_handle(refPlace.get_handle())
            place.add_placeref(placeRef)
#        tag.set_color("#EF2929")
        with DbTxn(_("Add Place"), db) as trans:
            phandle = db.add_place(place, trans)

            LOG.debug('Place added: ' + place.get_name().get_value() + ' ' +
                      phandle)
        return place
コード例 #5
0
ファイル: editevent.py プロジェクト: oluul/gramps
    def query_response(self):
        with DbTxn(
                _("Delete Event (%s)") % self.event.get_gramps_id(),
                self.db) as trans:
            self.db.disable_signals()

            ev_handle_list = [self.event.get_handle()]

            for handle in self.person_list:
                person = self.db.get_person_from_handle(handle)
                person.remove_handle_references('Event', ev_handle_list)
                self.db.commit_person(person, trans)

            for handle in self.family_list:
                family = self.db.get_family_from_handle(handle)
                family.remove_handle_references('Event', ev_handle_list)
                self.db.commit_family(family, trans)

            self.db.enable_signals()
            self.db.remove_event(self.event.get_handle(), trans)
コード例 #6
0
 def process(self):
     sql = self.openSQL()
     total = (sql.query("select count(*) from note;")[0][0] +
              sql.query("select count(*) from person;")[0][0] +
              sql.query("select count(*) from event;")[0][0] +
              sql.query("select count(*) from family;")[0][0] +
              sql.query("select count(*) from repository;")[0][0] +
              sql.query("select count(*) from place;")[0][0] +
              sql.query("select count(*) from media;")[0][0] +
              sql.query("select count(*) from tag;")[0][0] +
              sql.query("select count(*) from citation;")[0][0] +
              sql.query("select count(*) from source;")[0][0])
     with DbTxn(_("CSV import"), self.db, batch=True) as self.trans:
         self.db.disable_signals()
         count = 0.0
         self.t = time.time()
         self._process(count, total, sql)
     sql.db.commit()
     sql.db.close()
     return None
コード例 #7
0
ファイル: editnote.py プロジェクト: dmccubbing/gramps
    def save(self, *obj):
        """Save the data."""
        self.ok_button.set_sensitive(False)

        self.update_note()

        if self.object_is_empty():
            ErrorDialog(
                _("Cannot save note"),
                _("No data exists for this note. Please "
                  "enter data or cancel the edit."))
            self.ok_button.set_sensitive(True)
            return

        (uses_dupe_id, id) = self._uses_duplicate_id()
        if uses_dupe_id:
            msg1 = _("Cannot save note. ID already exists.")
            msg2 = _("You have attempted to use the existing Gramps ID with "
                     "value %(id)s. This value is already used. Please "
                     "enter a different ID or leave "
                     "blank to get the next available ID value.") % {
                         'id': id
                     }
            ErrorDialog(msg1, msg2)
            self.ok_button.set_sensitive(True)
            return

        with DbTxn('', self.db) as trans:
            if not self.obj.get_handle():
                self.db.add_note(self.obj, trans)
                msg = _("Add Note")
            else:
                if not self.obj.get_gramps_id():
                    self.obj.set_gramps_id(self.db.find_next_note_gramps_id())
                self.db.commit_note(self.obj, trans)
                msg = _("Edit Note")
            trans.set_description(msg)

        if self.callback:
            self.callback(self.obj.get_handle())
        self.close()
コード例 #8
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST.
        We assume this is what we obtain
        """
        if not sel_data:
            return

        files = sel_data.get_uris()
        photo = None

        for file in files:
            protocol, site, mfile, j, k, l = urlparse(file)
            if protocol == "file":
                name = url2pathname(mfile)
                mime = get_type(name)
                if not is_valid_type(mime):
                    return
                photo = Media()
                self.uistate.set_busy_cursor(True)
                photo.set_checksum(create_checksum(name))
                self.uistate.set_busy_cursor(False)
                base_dir = str(media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_media(photo, trans)

        if photo:
            self.uistate.set_active(photo.handle, "Media")

        widget.emit_stop_by_name('drag_data_received')
コード例 #9
0
ファイル: editsource.py プロジェクト: vperic/gramps
    def save(self, *obj):
        self.ok_button.set_sensitive(False)
        if self.object_is_empty():
            ErrorDialog(
                _("Cannot save source"),
                _("No data exists for this source. Please "
                  "enter data or cancel the edit."))
            self.ok_button.set_sensitive(True)
            return

        (uses_dupe_id, id) = self._uses_duplicate_id()
        if uses_dupe_id:
            prim_object = self.get_from_gramps_id(id)
            name = prim_object.get_title()
            msg1 = _("Cannot save source. ID already exists.")
            msg2 = _("You have attempted to use the existing Gramps ID with "
                     "value %(id)s. This value is already used by '"
                     "%(prim_object)s'. Please enter a different ID or leave "
                     "blank to get the next available ID value.") % {
                         'id': id,
                         'prim_object': name
                     }
            ErrorDialog(msg1, msg2)
            self.ok_button.set_sensitive(True)
            return

        with DbTxn('', self.db) as trans:
            if not self.obj.get_handle():
                self.db.add_source(self.obj, trans)
                msg = _("Add Source (%s)") % self.obj.get_title()
            else:
                if not self.obj.get_gramps_id():
                    self.obj.set_gramps_id(
                        self.db.find_next_source_gramps_id())
                self.db.commit_source(self.obj, trans)
                msg = _("Edit Source (%s)") % self.obj.get_title()
            trans.set_description(msg)

        self.close()
        if self.callback:
            self.callback(self.obj)
コード例 #10
0
    def __get_places(self, obj):
        gov_id = self.entry.get_text()
        to_do = [gov_id]
        try:
            preferred_lang = config.get('preferences.place-lang')
        except AttributeError:
            fmt = config.get('preferences.place-format')
            pf = _pd.get_formats()[fmt]
            preferred_lang = pf.language
        if len(preferred_lang) != 2:
            preferred_lang = 'de'
        visited = {}

        if not self.type_dic:
            self.__get_types()

        with DbTxn(_('Add GOV-id place %s') % gov_id, self.dbstate.db) as trans:
            while to_do:
                gov_id = to_do.pop()
                place = self.dbstate.db.get_place_from_gramps_id(gov_id)
                if place is not None:
                    visited[gov_id] = (place, [])
                else:
                    place, ref_list = self.__get_place(gov_id, self.type_dic,
                                                       preferred_lang)
                    if place.get_name().get_value is not '':
                        self.dbstate.db.add_place(place, trans)
                        visited[gov_id] = (place, ref_list)
                        for ref, date in ref_list:
                            if (ref not in to_do) and (ref not in visited):
                                to_do.append(ref)

            for place, ref_list in visited.values():
                if len(ref_list) > 0:
                    for ref, date in ref_list:
                        handle = visited[ref][0].handle
                        place_ref = PlaceRef()
                        place_ref.ref = handle
                        place_ref.set_date_object(date)
                        place.add_placeref(place_ref)
                    self.dbstate.db.commit_place(place, trans)
コード例 #11
0
ファイル: editplace.py プロジェクト: cicl06/gramps
    def save(self, *obj):
        self.ok_button.set_sensitive(False)

        if self.obj.get_name().get_value().strip() == '':
            msg1 = _("Cannot save place. Name not entered.")
            msg2 = _("You must enter a name before saving.")
            ErrorDialog(msg1, msg2)
            self.ok_button.set_sensitive(True)
            return

        (uses_dupe_id, id) = self._uses_duplicate_id()
        if uses_dupe_id:
            prim_object = self.get_from_gramps_id(id)
            name = place_displayer.display(self.db, prim_object)
            msg1 = _("Cannot save place. ID already exists.")
            msg2 = _("You have attempted to use the existing Gramps ID with "
                     "value %(id)s. This value is already used by '"
                     "%(prim_object)s'. Please enter a different ID or leave "
                     "blank to get the next available ID value.") % {
                         'id': id,
                         'prim_object': name
                     }
            ErrorDialog(msg1, msg2)
            self.ok_button.set_sensitive(True)
            return

        with DbTxn('', self.db) as trans:
            place_title = place_displayer.display(self.db, self.obj)
            if not self.obj.get_handle():
                self.db.add_place(self.obj, trans)
                msg = _("Add Place (%s)") % place_title
            else:
                if not self.obj.get_gramps_id():
                    self.obj.set_gramps_id(self.db.find_next_place_gramps_id())
                self.db.commit_place(self.obj, trans)
                msg = _("Edit Place (%s)") % place_title
            trans.set_description(msg)

        self.close()
        if self.callback:
            self.callback(self.obj)
コード例 #12
0
ファイル: libpersonview.py プロジェクト: vperic/gramps
    def delete_person_response(self):
        """
        Deletes the person from the database.
        """
        # set the busy cursor, so the user knows that we are working
        self.uistate.set_busy_cursor(True)

        # create the transaction
        with DbTxn('', self.dbstate.db) as trans:
        
            # create name to save
            person = self.active_person
            active_name = _("Delete Person (%s)") % name_displayer.display(person)

            # delete the person from the database
            # Above will emit person-delete, which removes the person via 
            # callback to the model, so row delete is signaled
            self.dbstate.db.delete_person_from_database(person, trans)
            trans.set_description(active_name)

        self.uistate.set_busy_cursor(False)
コード例 #13
0
 def post(self) -> Response:
     """Post a new object."""
     require_permissions([PERM_ADD_OBJ])
     obj = self._parse_object()
     if not obj:
         abort(400)
     db_handle = self.db_handle_writable
     with DbTxn("Add objects", db_handle) as trans:
         try:
             add_object(db_handle, obj, trans, fail_if_exists=True)
         except ValueError:
             abort(400)
         trans_dict = transaction_to_json(trans)
     # update search index
     indexer: SearchIndexer = current_app.config["SEARCH_INDEXER"]
     with indexer.get_writer(overwrite=False, use_async=True) as writer:
         for _trans_dict in trans_dict:
             handle = _trans_dict["handle"]
             class_name = _trans_dict["_class"]
             indexer.add_or_update_object(writer, handle, db_handle, class_name)
     return self.response(201, trans_dict, total_items=len(trans_dict))
コード例 #14
0
    def run(self):
        """Tool processing."""
        db = self.dbstate.get_database()
        filter_ = self.__opt("families").get_filter()
        rel_value = int(self.__opt("relationship").get_value())
        rel = FamilyRelType._DATAMAP[rel_value]
        all_families = db.iter_family_handles()
        families = filter_.apply(db, all_families)
        num = len(families)
        name = _("Family Relationship Tool")

        with DbTxn(name, db, batch=True) as self.trans:
            db.disable_signals()
            self.progress.set_pass(_('Process relationships...'), num)
            for handle in families:
                family = db.get_family_from_handle(handle)
                family.set_relationship(rel)
                db.commit_family(family, self.trans)
                self.progress.step()
        db.enable_signals()
        db.request_rebuild()
コード例 #15
0
ファイル: tags.py プロジェクト: uli22/gramps
 def tag_selected_rows(self, tag_handle):
     """
     Tag the selected rows with the given tag.
     """
     view = self.uistate.viewmanager.active_page
     selected = view.selected_handles()
     # Make the dialog modal so that the user can't start another
     # database transaction while the one setting tags is still running.
     pmon = progressdlg.ProgressMonitor(progressdlg.GtkProgressDialog,
             ("", self.uistate.window, Gtk.DialogFlags.MODAL), popup_time=2)
     status = progressdlg.LongOpStatus(msg=_("Adding Tags"),
                                       total_steps=len(selected),
                                       interval=len(selected)//20)
     pmon.add_op(status)
     tag = self.db.get_tag_from_handle(tag_handle)
     msg = _('Tag Selection (%s)') % tag.get_name()
     with DbTxn(msg, self.db) as trans:
         for object_handle in selected:
             status.heartbeat()
             view.add_tag(trans, object_handle, tag_handle)
     status.end()
コード例 #16
0
ファイル: editform.py プロジェクト: uli22/addons-source
    def save(self, button):
        """
        Called when the user clicks the OK button.
        """
        with DbTxn(self.get_menu_title(), self.db) as trans:
            if not self.event.get_handle():
                self.db.add_event(self.event, trans)

            citation_handle = self.citation.get_handle()
            if not self.citation.get_handle():
                self.db.add_citation(self.citation, trans)
                self.event.add_citation(self.citation.get_handle())
            else:
                self.db.commit_citation(self.citation, trans)

            self.headings.save()
            self.details.save(trans)

            self.db.commit_event(self.event, trans)
        self.close()
        self.callback()
コード例 #17
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data, 
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST. 
        We assume this is what we obtain
        """
        if not sel_data:
            return
        #modern file managers provide URI_LIST. For Windows split sel_data.data
        files = sel_data.get_uris()
        for file in files:
            if win():
                clean_string = conv_to_unicode(
                    file.replace('\0', ' ').replace("\r", " ").strip(), None)
            else:
                clean_string = file
            protocol, site, mfile, j, k, l = urlparse(clean_string)
            if protocol == "file":
                name = url2pathname(mfile)
                mime = get_type(name)
                if not is_valid_type(mime):
                    return
                photo = MediaObject()
                self.uistate.set_busy_cursor(True)
                photo.set_checksum(create_checksum(name))
                self.uistate.set_busy_cursor(False)
                base_dir = str(media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_object(photo, trans)
        widget.emit_stop_by_name('drag_data_received')
コード例 #18
0
ファイル: test_jwt.py プロジェクト: zackJKnight/gramps-webapi
 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="******", role=ROLE_GUEST)
     sqlauth.add_user(name="admin", password="******", role=ROLE_OWNER)
     dbstate = cls.app.config["DB_MANAGER"].get_db(force_unlock=True)
     with DbTxn("Add test objects", dbstate.db) as trans:
         _add_person(Person.MALE, "John", "Allen", trans, dbstate.db)
         _add_person(Person.FEMALE,
                     "Jane",
                     "Secret",
                     trans,
                     dbstate.db,
                     private=True)
     dbstate.db.close()
コード例 #19
0
    def lock_events(self, date, lock_no_date):
        with DbTxn(_("Set Privacy Tool"), self.db, batch=True) as self.trans:
            self.db.disable_signals()
            event_list = list(self.db.iter_events())

            filter_option = self.options.menu.get_option_by_name(
                'event_filter')
            event_filter = filter_option.get_filter()
            filtered_event_handles = event_filter.apply(
                self.db, self.db.iter_event_handles())

            self.progress.set_pass(_('Set events private..'),
                                   len(filtered_event_handles))

            cnt = [0, 0]
            for Event in event_list:
                if Event.handle not in filtered_event_handles:
                    continue
                event_date = Event.get_date_object()
                set_privacy = None
                if event_date.get_year() == 0 and lock_no_date:
                    set_privacy = True
                    cnt[0] += 1
                elif event_date.get_year() == 0 and not lock_no_date:
                    set_privacy = False
                    cnt[1] += 1
                elif event_date.get_year() != 0 and event_date >= date:
                    set_privacy = True
                    cnt[0] += 1
                else:
                    set_privacy = False
                    cnt[1] += 1
                if set_privacy is not None and set_privacy != Event.private:
                    Event.set_privacy(set_privacy)
                    self.db.commit_event(Event, self.trans)
                self.progress.step()
        self.db.enable_signals()
        self.db.request_rebuild()
        self.cnt.append(("events", cnt[0], cnt[1]))
コード例 #20
0
    def fix_media(self, button):
        """
        Fix paths to moved media files.
        """
        progress = ProgressMeter(self.window_name, can_cancel=True,
                                 parent=self.window)
        progress.set_pass(_('Fixing file paths'), len(self.moved_files))

        with DbTxn(_("Fix media paths"), self.db, batch=True) as trans:

            for handle, new_path in self.moved_files:
                media = self.db.get_media_from_handle(handle)
                media.set_path(new_path)
                self.db.commit_media(media, trans)

                progress.step()
                if progress.get_cancelled():
                    break

        self.models[0].clear()
        self.show_tabs()
        progress.close()
コード例 #21
0
ファイル: Dates.py プロジェクト: Taapeli/stk-addons
 def __execute(self, obj):
     with DbTxn(_("Correcting invalid dates"),
                self.dbstate.db) as self.trans:
         selected_handles = self.uistate.viewmanager.active_page.selected_handles(
         )
         num_places = len(selected_handles)
         for eventhandle in selected_handles:
             event = self.dbstate.db.get_event_from_handle(eventhandle)
             print(event)
             dateobj = event.get_date_object()
             datestr = dateobj.get_text()
             if dateobj.is_valid():
                 print(dateobj, "is valid")
                 continue
             if datestr == "":
                 print(dateobj, "is blank")
                 continue
             print(datestr, "is INvalid")
             newdate = self.fix_date(datestr)
             print("newdate:", newdate)
             dateobj.set_text_value(newdate)
             self.dbstate.db.commit_event(event, self.trans)
コード例 #22
0
ファイル: db_test.py プロジェクト: schoonc/gramps
 def tearDown(self):
     with DbTxn('Remove test objects', self.db) as trans:
         for handle in self.handles['Person']:
             self.db.remove_person(handle, trans)
         for handle in self.handles['Family']:
             self.db.remove_family(handle, trans)
         for handle in self.handles['Event']:
             self.db.remove_event(handle, trans)
         for handle in self.handles['Place']:
             self.db.remove_place(handle, trans)
         for handle in self.handles['Repository']:
             self.db.remove_repository(handle, trans)
         for handle in self.handles['Source']:
             self.db.remove_source(handle, trans)
         for handle in self.handles['Citation']:
             self.db.remove_citation(handle, trans)
         for handle in self.handles['Media']:
             self.db.remove_media(handle, trans)
         for handle in self.handles['Note']:
             self.db.remove_note(handle, trans)
         for handle in self.handles['Tag']:
             self.db.remove_tag(handle, trans)
コード例 #23
0
    def lock_media(self, date, lock_no_date):
        with DbTxn(_("Set Privacy Tool"), self.db, batch=True) as self.trans:
            self.db.disable_signals()
            media_list = list(self.db.iter_media())

            filter_option = self.options.menu.get_option_by_name(
                'media_filter')
            media_filter = filter_option.get_filter()
            filtered_media_handles = media_filter.apply(
                self.db, self.db.iter_media_handles())

            self.progress.set_pass(_('Set media private..'),
                                   len(filtered_media_handles))

            cnt = [0, 0]
            for Media in media_list:
                if Media.handle not in filtered_media_handles:
                    continue
                media_date = Media.get_date_object()
                set_privacy = None
                if media_date.get_year() == 0 and lock_no_date:
                    set_privacy = True
                    cnt[0] += 1
                elif media_date.get_year() == 0 and not lock_no_date:
                    set_privacy = False
                    cnt[1] += 1
                elif media_date.get_year() != 0 and media_date >= date:
                    set_privacy = True
                    cnt[0] += 1
                else:
                    set_privacy = False
                    cnt[1] += 1
                if set_privacy is not None and set_privacy != Media.private:
                    Media.set_privacy(set_privacy)
                    self.db.commit_media(Media, self.trans)
                self.progress.step()
        self.db.enable_signals()
        self.db.request_rebuild()
        self.cnt.append(("media", cnt[0], cnt[1]))
コード例 #24
0
 def addRepository(repositoryName, repositoryUrl, reftag):
     ridno = db.find_next_repository_gramps_id()
     repository = Repository()
     repositoryType = RepositoryType()
     repositoryType.set(RepositoryType.ARCHIVE)
     repository.set_type(repositoryType)
     repository.set_gramps_id(ridno)
     repository.set_name(repositoryName)
     urlList = []
     #        for urlPath in repositoryUrls:
     url = Url()
     url.set_path(repositoryUrl)
     url.set_description('Sshy')
     url.set_type(UrlType.WEB_HOME)
     urlList.append(url)
     repository.set_url_list(urlList)
     repository.set_change_time(chgtime)
     if reftag != None:
         repository.add_tag(reftag.get_handle())
     with DbTxn(_("Add Repository"), db) as trans:
         rhandle = db.add_repository(repository, trans)
     return repository
コード例 #25
0
ファイル: JSONImport.py プロジェクト: killes/addons-source
def importData(dbase, filename, user):
    """Function called by Gramps to import data on persons in CSV format."""
    dbase.disable_signals()
    try:
        with DbTxn(_("JSON import"), dbase, batch=True) as trans:
            with OpenFileOrStdin(filename, encoding="utf-8") as fp:
                line = fp.readline()
                while line:
                    json = ast.literal_eval(line)
                    obj = from_struct(json)
                    if json["_class"] == "Person":
                        dbase.add_person(obj, trans)
                    elif json["_class"] == "Family":
                        dbase.add_family(obj, trans)
                    elif json["_class"] == "Event":
                        dbase.add_event(obj, trans)
                    elif json["_class"] == "MediaObject":
                        dbase.add_object(obj, trans)
                    elif json["_class"] == "Repository":
                        dbase.add_repository(obj, trans)
                    elif json["_class"] == "Tag":
                        dbase.add_tag(obj, trans)
                    elif json["_class"] == "Source":
                        dbase.add_source(obj, trans)
                    elif json["_class"] == "Citation":
                        dbase.add_citation(obj, trans)
                    elif json["_class"] == "Note":
                        dbase.add_note(obj, trans)
                    elif json["_class"] == "Place":
                        dbase.add_place(obj, trans)
                    else:
                        LOG.warn("ignored: " + json)
                    line = fp.readline()
    except EnvironmentError as err:
        user.notify_error(_("%s could not be opened\n") % filename, str(err))

    dbase.enable_signals()
    dbase.request_rebuild()
コード例 #26
0
ファイル: JSONImport.py プロジェクト: vantu5z/addons-source
def importData(db, filename, user):
    """Function called by Gramps to import data on persons in CSV format."""
    db.disable_signals()

    try:
        with DbTxn(_("JSON import"), db, batch=True) as trans:
            with OpenFileOrStdin(filename, encoding="utf-8") as fp:
                line = fp.readline()
                while line:
                    obj = from_json(line)
                    if isinstance(obj, Person):
                        db.add_person(obj, trans)
                    elif isinstance(obj, Family):
                        db.add_family(obj, trans)
                    elif isinstance(obj, Event):
                        db.add_event(obj, trans)
                    elif isinstance(obj, Media):
                        db.add_media(obj, trans)
                    elif isinstance(obj, Repository):
                        db.add_repository(obj, trans)
                    elif isinstance(obj, Tag):
                        db.add_tag(obj, trans)
                    elif isinstance(obj, Source):
                        db.add_source(obj, trans)
                    elif isinstance(obj, Citation):
                        db.add_citation(obj, trans)
                    elif isinstance(obj, Note):
                        db.add_note(obj, trans)
                    elif isinstance(obj, Place):
                        db.add_place(obj, trans)
                    else:
                        LOG.warn("ignored: " + data)
                    line = fp.readline()
    except EnvironmentError as err:
        user.notify_error(_("%s could not be opened\n") % filename, str(err))

    db.enable_signals()
    db.request_rebuild()
コード例 #27
0
 def post(self) -> Response:
     """Post a new object."""
     require_permissions([PERM_ADD_OBJ])
     mime = request.content_type
     if not mime:
         abort(HTTPStatus.NOT_ACCEPTABLE)
     checksum, f = process_file(request.stream)
     base_dir = current_app.config.get("MEDIA_BASE_DIR", "")
     media_handler = MediaHandler(base_dir)
     media_handler.upload_file(f, checksum, mime)
     path = media_handler.get_default_filename(checksum, mime)
     db_handle = self.db_handle_writable
     obj = Media()
     obj.set_checksum(checksum)
     obj.set_path(path)
     obj.set_mime_type(mime)
     with DbTxn("Add object", db_handle) as trans:
         try:
             add_object(db_handle, obj, trans)
         except ValueError:
             abort(400)
         trans_dict = transaction_to_json(trans)
     return self.response(201, trans_dict, total_items=len(trans_dict))
コード例 #28
0
 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)
コード例 #29
0
    def __removeTag(self, tag_handle):
        counter = 0
        iter_people = self.dbstate.db.iter_person_handles()
        self.filter_option = self.options.menu.get_option_by_name('filter')
        self.filter = self.filter_option.get_filter()
        people = self.filter.apply(self.dbstate.db, iter_people)

        with DbTxn(_("Remove Tag Tool"), self.db, batch=True) as self.trans:
            self.db.disable_signals()
            num_people = len(people)
            self.progress.set_pass(_('Removing tags...'), num_people)
            for person_handle in people:
                person = self.dbstate.db.get_person_from_handle(person_handle)
                if tag_handle in person.get_tag_list():
                    person.remove_tag(tag_handle)
                    self.db.commit_person(person, self.trans)
                    counter += 1
        self.db.enable_signals()
        self.db.request_rebuild()

        text = _("Tag removed from {} people.\n")
        text_f = text.format(str(counter))
        OkDialog("INFO", text_f, parent=self.window)
コード例 #30
0
    def on_ok_clicked(self, obj):
        with DbTxn(_("Extract Place data"), self.db, batch=True) as self.trans:
            self.db.disable_signals()
            changelist = [node for node in self.iter_list
                          if self.model.get_value(node, 0)]

            for change in changelist:
                row = self.model[change]
                place = self.db.get_place_from_handle(row[6])
                location = ('', '', '', row[2], '', row[3], row[5])
                self.place_import.store_location(location, place.handle)
                if row[2]:
                    place.set_name(PlaceName(value=row[2]))
                place.set_type(PlaceType.CITY)
                if row[4]:
                    place.set_code(row[4])
                self.db.commit_place(place, self.trans)

            self.place_import.generate_hierarchy(self.trans)

        self.db.enable_signals()
        self.db.request_rebuild()
        self.close()