#!/usr/bin/env python3 """Add a contact to an Evolution Data Server address book (which syncs it on, e.g. to Nextcloud via CardDAV). eds-add-contact.py books -> JSON {"books": [...], "default": uid or null} eds-add-contact.py add -> reads JSON {first, last, org, number, book?} on stdin, prints JSON {"uid": ...} The default book is the one GNOME Contacts uses for new contacts (folks' primary store), else EDS's own default address book. """ import json import sys import gi gi.require_version("EDataServer", "1.2") gi.require_version("EBookContacts", "1.2") gi.require_version("EBook", "1.2") from gi.repository import EBook, EBookContacts, EDataServer as EDS, Gio # noqa: E402 # Server-generated or automatic books nobody adds contacts to by hand. SKIP_NAMES = {"accounts", "recently contacted", "recent"} def esc(v): return v.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n") def default_uid(reg): try: if "org.freedesktop.folks" in Gio.Settings.list_schemas(): store = Gio.Settings.new("org.freedesktop.folks").get_string("primary-store") if store.startswith("eds:"): return store[4:] except Exception: pass src = reg.ref_default_address_book() return src.get_uid() if src else None def books(reg): out = [] for s in reg.list_enabled(EDS.SOURCE_EXTENSION_ADDRESS_BOOK): if s.get_display_name().lower() in SKIP_NAMES: continue ext = s.get_extension(EDS.SOURCE_EXTENSION_ADDRESS_BOOK) if ext.get_backend_name() == "ldap": continue parent = reg.ref_source(s.get_parent()) if s.get_parent() else None out.append({ "uid": s.get_uid(), "name": s.get_display_name(), "account": parent.get_display_name() if parent else "", }) return out def add(reg, req): uid = req.get("book") or default_uid(reg) source = reg.ref_source(uid) if uid else None if source is None: raise SystemExit("No address book to add the contact to.") client = EBook.BookClient.connect_sync(source, 30, None) if client.is_readonly(): raise SystemExit(f"The address book \"{source.get_display_name()}\" is read-only.") first, last, org = (req.get(k, "").strip() for k in ("first", "last", "org")) full = " ".join(p for p in (first, last) if p) or org or req["number"] lines = ["BEGIN:VCARD", "VERSION:3.0", f"N:{esc(last)};{esc(first)};;;", f"FN:{esc(full)}"] if org: lines.append(f"ORG:{esc(org)}") lines += [f"TEL;TYPE=CELL:{req['number']}", "END:VCARD"] contact = EBookContacts.Contact.new_from_vcard("\r\n".join(lines)) ok, new_uid = client.add_contact_sync(contact, EBookContacts.BookOperationFlags.NONE, None) json.dump({"uid": new_uid, "book": source.get_display_name()}, sys.stdout) def main(): reg = EDS.SourceRegistry.new_sync(None) cmd = sys.argv[1] if len(sys.argv) > 1 else "books" if cmd == "books": json.dump({"books": books(reg), "default": default_uid(reg)}, sys.stdout) elif cmd == "add": add(reg, json.load(sys.stdin)) else: raise SystemExit(f"unknown command {cmd}") main()