Example #1
0
def get_extended_attributes(
    db_handle: DbReadBase, obj: GrampsObject, args: Optional[Dict] = None
) -> Dict:
    """Get extended attributes for a GrampsObject."""
    args = args or {}
    result = {}
    do_all = False
    if "all" in args["extend"]:
        do_all = True
    if (do_all or "child_ref_list" in args["extend"]) and hasattr(
        obj, "child_ref_list"
    ):
        result["children"] = [
            db_handle.get_person_from_handle(child_ref.ref)
            for child_ref in obj.child_ref_list
        ]
    if (do_all or "citation_list" in args["extend"]) and hasattr(obj, "citation_list"):
        result["citations"] = [
            db_handle.get_citation_from_handle(handle) for handle in obj.citation_list
        ]
    if (do_all or "event_ref_list" in args["extend"]) and hasattr(
        obj, "event_ref_list"
    ):
        result["events"] = [
            db_handle.get_event_from_handle(event_ref.ref)
            for event_ref in obj.event_ref_list
        ]
    if (do_all or "media_list" in args["extend"]) and hasattr(obj, "media_list"):
        result["media"] = [
            db_handle.get_media_from_handle(media_ref.ref)
            for media_ref in obj.media_list
        ]
    if (do_all or "note_list" in args["extend"]) and hasattr(obj, "note_list"):
        result["notes"] = [
            db_handle.get_note_from_handle(handle) for handle in obj.note_list
        ]
    if (do_all or "person_ref_list" in args["extend"]) and hasattr(
        obj, "person_ref_list"
    ):
        result["people"] = [
            db_handle.get_person_from_handle(person_ref.ref)
            for person_ref in obj.person_ref_list
        ]
    if (do_all or "reporef_list" in args["extend"]) and hasattr(obj, "reporef_list"):
        result["repositories"] = [
            db_handle.get_repository_from_handle(repo_ref.ref)
            for repo_ref in obj.reporef_list
        ]
    if (do_all or "tag_list" in args["extend"]) and hasattr(obj, "tag_list"):
        result["tags"] = [
            db_handle.get_tag_from_handle(handle) for handle in obj.tag_list
        ]
    if (do_all or "backlinks" in args["extend"]) and hasattr(obj, "backlinks"):
        result["backlinks"] = {}
        for class_name, backlinks in obj.backlinks.items():
            result["backlinks"][class_name] = [
                db_handle.method("get_%s_from_handle", class_name.upper())(handle)
                for handle in backlinks
            ]
    return result
Example #2
0
def get_object_timestamps(db_handle: DbReadBase):
    """Get a dictionary with change timestamps of all objects in the DB."""
    d = {}
    for class_name in PRIMARY_GRAMPS_OBJECTS:
        d[class_name] = set()
        iter_method = db_handle.method("iter_%s_handles", class_name)
        for handle in iter_method():
            query_method = db_handle.method("get_%s_from_handle", class_name)
            obj = query_method(handle)
            d[class_name].add((handle, datetime.fromtimestamp(obj.change)))
    return d
Example #3
0
def get_soundex(db_handle: DbReadBase, obj: GrampsObject,
                gramps_class_name: str) -> str:
    """Return soundex code."""
    if gramps_class_name == "Family":
        if obj.father_handle is not None:
            person = db_handle.get_person_from_handle(obj.father_handle)
        elif obj.mother_handle is not None:
            person = db_handle.get_person_from_handle(obj.mother_handle)
    else:
        person = obj
    return soundex(person.get_primary_name().get_surname())
Example #4
0
def prepare_options(db_handle: DbReadBase, args: Dict):
    """Prepare the export options."""
    options = ExportOptions()
    options.private = args["private"]
    options.living = LIVING_FILTERS[args["living"]]
    options.current_year = args["current_year"]
    options.years_after_death = args["years_after_death"]
    options.reference = args["reference"]
    options.include_individuals = int(args["include_individuals"])
    options.include_marriages = int(args["include_marriages"])
    options.include_children = int(args["include_children"])
    options.include_places = int(args["include_places"])
    options.include_witnesses = int(args["include_witnesses"])
    options.include_media = int(args["include_media"])
    options.translate_headers = int(args["translate_headers"])
    options.compression = int(args["compress"])
    if args["person"] is None:
        if args["gramps_id"] is not None or args["handle"] is not None:
            abort(422)
    else:
        if args["gramps_id"] is not None:
            gramps_id = args["gramps_id"]
            if db_handle.get_person_from_gramps_id(gramps_id) is None:
                abort(422)
        else:
            try:
                person = db_handle.get_person_from_handle(args["handle"])
            except HandleError:
                abort(422)
            gramps_id = person.gramps_id
        try:
            options.set_person_filter(args["person"], gramps_id)
        except ValueError:
            abort(422)
    if args["event"] is not None:
        try:
            options.set_event_filter(args["event"])
        except ValueError:
            abort(422)
    if args["note"] is not None:
        try:
            options.set_note_filter(args["note"])
        except ValueError:
            abort(422)
    try:
        options.set_proxy_order(args["sequence"])
    except ValueError:
        abort(422)
    if args["locale"] is not None:
        options.locale = get_locale_for_language(args["locale"])
        if options.locale is None:
            abort(422)
    return options
Example #5
0
def get_person_by_handle(db_handle: DbReadBase,
                         handle: Handle) -> Union[Person, Dict]:
    """Safe get person by handle."""
    try:
        return db_handle.get_person_from_handle(handle)
    except HandleError:
        return {}
Example #6
0
def get_place_by_handle(db_handle: DbReadBase,
                        handle: Handle) -> Union[Place, Dict]:
    """Safe get place by handle."""
    try:
        return db_handle.get_place_from_handle(handle)
    except HandleError:
        return {}
Example #7
0
def get_missing_media_file_handles(
    db_handle: DbReadBase, handles: List[str]
) -> List[str]:
    """Filter media handles returning only ones where the file is missing."""
    objects = [db_handle.get_media_from_handle(handle) for handle in handles]
    objects_missing = filter_missing_files(objects)
    return [obj.handle for obj in objects_missing]
Example #8
0
def get_citation_grampsids(db: DbReadBase,
                           obj: GrampsObject) -> List[GrampsId]:
    """Get the Gramps IDs of direct citations of a Gramps object."""
    return [
        db.get_citation_from_handle(handle).gramps_id
        for handle in obj.get_citation_list()
    ]
Example #9
0
def get_event_place_grampsid(db: DbReadBase,
                             event: Event) -> Optional[GrampsId]:
    """Get the event's place."""
    try:
        return db.get_place_from_handle(event.place).gramps_id
    except (HandleError, AttributeError):
        return None
Example #10
0
def get_place_by_handle(db_handle: DbReadBase,
                        handle: Handle) -> Optional[Place]:
    """Safe get place by handle."""
    try:
        return db_handle.get_place_from_handle(handle)
    except HandleError:
        return None
Example #11
0
def get_person_by_handle(db_handle: DbReadBase,
                         handle: Handle) -> Optional[Person]:
    """Safe get person by handle."""
    try:
        return db_handle.get_person_from_handle(handle)
    except HandleError:
        return None
Example #12
0
def match_dates(
    db_handle: DbReadBase, gramps_class_name: str, handles: List[Handle], date_mask: str
):
    """Match dates based on a date mask or range."""
    check_range = False
    if "-" in date_mask:
        check_range = True
        start, end = date_mask.split("-")
        if "/" in start:
            year, month, day = start.split("/")
            start_date = Date((int(year), int(month), int(day)))
        else:
            start_date = None
        if "/" in end:
            year, month, day = end.split("/")
            end_date = Date((int(year), int(month), int(day)))
        else:
            end_date = None

    query_method = db_handle.method("get_%s_from_handle", gramps_class_name)
    result = []
    for handle in handles:
        obj = query_method(handle)
        date = obj.get_date_object()
        if date.is_valid():
            if check_range:
                if match_date_range(date, start_date, end_date):
                    result.append(handle)
            else:
                if match_date(date, date_mask):
                    result.append(handle)
    return result
Example #13
0
def get_event_participants_for_handle(
    db_handle: DbReadBase,
    handle: Handle,
    locale: GrampsLocale = glocale,
) -> Dict:
    """Get event participants given a handle."""
    result = {"people": [], "families": []}
    seen = set()  # to avoid duplicates
    for class_name, backref_handle in db_handle.find_backlink_handles(
        handle, include_classes=["Person", "Family"]
    ):
        if backref_handle in seen:
            continue
        seen.add(backref_handle)
        if class_name == "Person":
            person = db_handle.get_person_from_handle(backref_handle)
            if not person:
                continue
            for event_ref in person.get_event_ref_list():
                if handle == event_ref.ref:
                    result["people"].append(
                        {
                            "role": locale.translation.sgettext(
                                event_ref.get_role().xml_str()
                            ),
                            "person": get_person_profile_for_handle(
                                db_handle, backref_handle, args=[], locale=locale
                            ),
                        }
                    )
        elif class_name == "Family":
            family = db_handle.get_family_from_handle(backref_handle)
            if not family:
                continue
            for event_ref in family.get_event_ref_list():
                if handle == event_ref.ref:
                    result["families"].append(
                        {
                            "role": locale.translation.sgettext(
                                event_ref.get_role().xml_str()
                            ),
                            "family": get_family_profile_for_handle(
                                db_handle, backref_handle, args=[], locale=locale
                            ),
                        }
                    )
    return result
Example #14
0
def get_person_filter(db_handle: DbReadBase,
                      args: Dict) -> Union[GenericFilter, None]:
    """Return the specified person filter."""
    if args["person"] is None:
        if args["gramps_id"] is not None or args["handle"] is not None:
            abort(422)
        return None

    if args["gramps_id"]:
        gramps_id = args["gramps_id"]
        if db_handle.get_person_from_gramps_id(gramps_id) is None:
            abort(422)
    else:
        try:
            person = db_handle.get_person_from_handle(args["handle"])
        except HandleError:
            abort(422)
        gramps_id = person.gramps_id

    person_filter = filters.GenericFilter()
    if args["person"] == "Descendants":
        person_filter.set_name(_("Descendants of %s") % gramps_id)
        person_filter.add_rule(
            filters.rules.person.IsDescendantOf([gramps_id, 1]))
    elif args["person"] == "DescendantFamilies":
        person_filter.set_name(_("Descendant Families of %s") % gramps_id)
        person_filter.add_rule(
            filters.rules.person.IsDescendantFamilyOf([gramps_id, 1]))
    elif args["person"] == "Ancestors":
        person_filter.set_name(_("Ancestors of %s") % gramps_id)
        person_filter.add_rule(
            filters.rules.person.IsAncestorOf([gramps_id, 1]))
    elif args["person"] == "CommonAncestor":
        person_filter.set_name(
            _("People with common ancestor with %s") % gramps_id)
        person_filter.add_rule(
            filters.rules.person.HasCommonAncestorWith([gramps_id]))
    else:
        person_filter = None
        filters.reload_custom_filters()
        for filter_class in filters.CustomFilters.get_filters("Person"):
            if args["person"] == filter_class.get_name():
                person_filter = filter_class
                break
    if person_filter is None:
        abort(422)
    return person_filter
Example #15
0
def get_event_date_from_handle(db: DbReadBase,
                               handle: Handle) -> Optional[str]:
    """Return a formatted date for the event."""
    try:
        date = db.get_event_from_handle(handle).get_date_object()
    except AttributeError:
        return None
    return dd.display(date) or None
Example #16
0
def get_event_profile_for_handle(db_handle: DbReadBase,
                                 handle: Handle) -> Optional[Dict]:
    """Get event profile given a handle."""
    try:
        obj = db_handle.get_event_from_handle(handle)
    except HandleError:
        return None
    return get_event_profile_for_object(db_handle, obj)
Example #17
0
def get_parents_grampsids(db: DbReadBase,
                          person: Person) -> Optional[GrampsId]:
    """Get the Gramps IDs of the family's parents."""
    handle = person.get_main_parents_family_handle()
    try:
        return db.get_family_from_handle(handle).gramps_id
    except HandleError:
        return None
Example #18
0
def get_place_profile_for_object(
    db_handle: DbReadBase,
    place: Place,
    locale: GrampsLocale = glocale,
    parent_places: bool = True,
) -> Dict[str, Any]:
    """Get place profile given a Place."""
    latitude, longitude = conv_lat_lon(place.lat, place.long, format="D.D8")
    profile = {
        "gramps_id":
        place.gramps_id,
        "type":
        _format_place_type(place.get_type(), locale=locale),
        "name":
        place.get_name().value,
        "alternate_names":
        [place_name.value for place_name in place.get_alternative_names()],
        "lat":
        float(latitude) if (latitude and longitude) else None,
        "long":
        float(longitude) if (latitude and longitude) else None,
    }
    if parent_places:
        parent_places_handles = []
        _place = place
        handle = None
        while True:
            for placeref in _place.get_placeref_list():
                handle = placeref.ref
                break
            if handle is None or handle in parent_places_handles:
                break
            _place = db_handle.get_place_from_handle(handle)
            if _place is None:
                break
            parent_places_handles.append(handle)
        profile["parent_places"] = [
            get_place_profile_for_object(
                db_handle=db_handle,
                place=db_handle.get_place_from_handle(parent_place),
                locale=locale,
                parent_places=False,
            ) for parent_place in parent_places_handles
        ]
    return profile
Example #19
0
def get_media_profile_for_handle(
    db_handle: DbReadBase, handle: Handle, args: List, locale: GrampsLocale = glocale
) -> Union[Media, Dict]:
    """Get media profile given a handle."""
    try:
        obj = db_handle.get_media_from_handle(handle)
    except HandleError:
        return {}
    return get_media_profile_for_object(db_handle, obj, args, locale=locale)
Example #20
0
def get_source_by_handle(db_handle: DbReadBase,
                         handle: Handle,
                         args: Optional[Dict] = None) -> Source:
    """Get a source and optional extended attributes."""
    args = args or {}
    obj = db_handle.get_source_from_handle(handle)
    if "extend" in args:
        obj.extended = get_extended_attributes(db_handle, obj, args)
    return obj
Example #21
0
def iter_obj_strings(
    db_handle: DbReadBase, ) -> Generator[Dict[str, Any], None, None]:
    """Iterate over object strings in the whole database."""
    for class_name in PRIMARY_GRAMPS_OBJECTS:
        iter_method = db_handle.method("iter_%s_handles", class_name)
        for handle in iter_method():
            obj_strings = obj_strings_from_handle(db_handle, class_name,
                                                  handle)
            if obj_strings:
                yield obj_strings
Example #22
0
def iter_obj_strings(
    db_handle: DbReadBase, ) -> Generator[Dict[str, Any], None, None]:
    """Iterate over object strings in the whole database."""
    for class_name in PRIMARY_GRAMPS_OBJECTS:
        query_method = db_handle.method("get_%s_from_handle", class_name)
        iter_method = db_handle.method("iter_%s_handles", class_name)
        for handle in iter_method():
            obj = query_method(handle)
            obj_string, obj_string_private = object_to_strings(obj)
            private = hasattr(obj, "private") and obj.private
            if obj_string:
                yield {
                    "class_name": class_name,
                    "handle": obj.handle,
                    "private": private,
                    "string": obj_string,
                    "string_private": obj_string_private,
                    "changed": datetime.fromtimestamp(obj.change),
                }
Example #23
0
def get_family_profile_for_handle(
        db_handle: DbReadBase,
        handle: Handle,
        with_events: bool = True) -> Optional[Family]:
    """Get family profile given a handle."""
    try:
        obj = db_handle.get_family_from_handle(handle)
    except HandleError:
        return None
    return get_family_profile_for_object(db_handle, obj, with_events)
Example #24
0
def get_backlinks(db_handle: DbReadBase, handle: Handle) -> Dict[str, List[Handle]]:
    """Get backlinks to a handle.

    Will return a dictionary of the form
    `{'object_type': ['handle1', 'handle2', ...], ...}`
    """
    backlinks = {}
    for obj_type, target_handle in db_handle.find_backlink_handles(handle):
        key = obj_type.lower()
        if key not in backlinks:
            backlinks[key] = []
        backlinks[key].append(target_handle)
    return backlinks
Example #25
0
def get_person_profile_for_handle(
    db_handle: DbReadBase,
    handle: Handle,
    with_family: bool = True,
    with_events: bool = True,
) -> Optional[Person]:
    """Get person profile given a handle."""
    try:
        obj = db_handle.get_person_from_handle(handle)
    except HandleError:
        return None
    return get_person_profile_for_object(db_handle, obj, with_family,
                                         with_events)
 def old_unchanged(self, db: DbReadBase, class_name: str, handle: str,
                   old_data: Dict) -> bool:
     """Check if the "old" object is still unchanged."""
     handle_func = db.method("get_%s_from_handle", class_name)
     try:
         obj = handle_func(handle)
     except HandleError:
         if old_data is None:
             return True
         return False
     obj_dict = json.loads(to_json(obj))
     if diff_items(class_name, old_data, obj_dict):
         return False
     return True
Example #27
0
def get_family_by_handle(
    db_handle: DbReadBase, handle: Handle, args: Optional[Dict] = None
) -> Union[Family, Dict]:
    """Get a family and optional extended attributes."""
    try:
        obj = db_handle.get_family_from_handle(handle)
    except HandleError:
        return {}
    args = args or {}
    if "extend" in args:
        obj.extended = get_extended_attributes(db_handle, obj, args)
        if "all" in args["extend"] or "father" in args["extend"]:
            obj.extended["father"] = get_person_by_handle(db_handle, obj.father_handle)
        if "all" in args["extend"] or "mother" in args["extend"]:
            obj.extended["mother"] = get_person_by_handle(db_handle, obj.mother_handle)
    return obj
Example #28
0
def get_rating(db_handle: DbReadBase, obj: GrampsObject) -> Tuple[int, int]:
    """Return rating based on citations."""
    count = 0
    confidence = 0
    if hasattr(obj, "citation_list"):
        count = len(obj.citation_list)
        if hasattr(obj, "extended") and "citations" in obj.extended:
            for citation in obj.extended["citations"]:
                if citation.confidence > confidence:
                    confidence = citation.confidence
        else:
            for handle in obj.citation_list:
                citation = db_handle.get_citation_from_handle(handle)
                if citation.confidence > confidence:
                    confidence = citation.confidence
    return count, confidence
Example #29
0
def obj_strings_from_handle(db_handle: DbReadBase, class_name: str,
                            handle) -> Optional[Dict[str, Any]]:
    """Return object strings from a handle and Gramps class name."""
    query_method = db_handle.method("get_%s_from_handle", class_name)
    obj = query_method(handle)
    obj_string, obj_string_private = object_to_strings(obj)
    private = hasattr(obj, "private") and obj.private
    if obj_string:
        return {
            "class_name": class_name,
            "handle": obj.handle,
            "private": private,
            "string": obj_string,
            "string_private": obj_string_private,
            "change": datetime.fromtimestamp(obj.change),
        }
    return None
Example #30
0
def get_bookmarks(db_handle: DbReadBase, namespace: str) -> Optional[List]:
    """Return bookmarks for a namespace."""
    result = None
    if namespace == "people":
        result = db_handle.get_bookmarks()
    elif namespace == "families":
        result = db_handle.get_family_bookmarks()
    elif namespace == "media":
        result = db_handle.get_media_bookmarks()
    elif namespace == "events":
        result = db_handle.get_event_bookmarks()
    elif namespace == "citations":
        result = db_handle.get_citation_bookmarks()
    elif namespace == "notes":
        result = db_handle.get_note_bookmarks()
    elif namespace == "places":
        result = db_handle.get_place_bookmarks()
    elif namespace == "sources":
        result = db_handle.get_source_bookmarks()
    elif namespace == "repositories":
        result = db_handle.get_repo_bookmarks()
    if result is None:
        abort(404)
    return result.get()