Source code for s365b.modules.exchange.vcf

"""vCard (``.vcf``) export of backed-up contacts.

Contacts become vCard 3.0 cards (RFC 2426), the version Outlook, Apple
Contacts, Google Contacts and Thunderbird all import; many cards go in one
file. Not in the export: contact photos (not backed up) and fields with no
vCard property (e.g. spouse, children, Yomi names).
"""

from __future__ import annotations

from typing import Any

[docs] FOLD_AT = 75 # octets per line, before the CRLF (RFC 2426 section 2.6)
[docs] ADDRESSES = (("businessAddress", "WORK"), ("homeAddress", "HOME"), ("otherAddress", "OTHER"))
[docs] def to_vcf(contacts: list[dict[str, Any]]) -> bytes: """Write contacts as vCards. Args: contacts: Graph contact objects, as backed up. Returns: The ``.vcf`` file, UTF-8 with CRLF line ends. """ lines: list[str] = [] for c in contacts: lines.extend(card(c)) return "".join(_fold(line) + "\r\n" for line in lines).encode()
[docs] def card(c: dict[str, Any]) -> list[str]: """One contact's vCard lines, unfolded. Args: c: A Graph contact object. Returns: The lines from ``BEGIN:VCARD`` to ``END:VCARD``. """ given, surname = _s(c.get("givenName")), _s(c.get("surname")) name = _s(c.get("displayName")) or " ".join(p for p in (given, surname) if p) if not name: emails = [_s(e.get("address")) for e in c.get("emailAddresses") or []] name = next((e for e in emails if e), "") or _s(c.get("companyName")) out = ["BEGIN:VCARD", "VERSION:3.0", f"FN:{_text(name)}"] parts = (surname, given, c.get("middleName"), c.get("title"), c.get("generation")) out.append("N:" + ";".join(_text(_s(p)) for p in parts)) if nick := _s(c.get("nickName")): out.append(f"NICKNAME:{_text(nick)}") company, department = _s(c.get("companyName")), _s(c.get("department")) if company or department: out.append(f"ORG:{_text(company)};{_text(department)}") if job := _s(c.get("jobTitle")): out.append(f"TITLE:{_text(job)}") for e in c.get("emailAddresses") or []: if address := _s(e.get("address")): out.append(f"EMAIL;TYPE=INTERNET:{_text(address)}") phones = [("CELL", c.get("mobilePhone"))] phones += [("WORK,VOICE", p) for p in c.get("businessPhones") or []] phones += [("HOME,VOICE", p) for p in c.get("homePhones") or []] for kind, number in phones: if number := _s(number): out.append(f"TEL;TYPE={kind}:{_text(number)}") for field, kind in ADDRESSES: a = c.get(field) or {} values = [_s(a.get(k)) for k in ("street", "city", "state", "postalCode")] values.append(_s(a.get("countryOrRegion"))) if any(values): out.append(f"ADR;TYPE={kind}:;;" + ";".join(_text(v) for v in values)) for im in c.get("imAddresses") or []: if im := _s(im): out.append(f"IMPP:{_text(im)}") if site := _s(c.get("businessHomePage")): out.append(f"URL:{_text(site)}") if birthday := _s(c.get("birthday"))[:10]: out.append(f"BDAY:{birthday}") if notes := _s(c.get("personalNotes")): out.append(f"NOTE:{_text(notes)}") if categories := [_text(_s(x)) for x in c.get("categories") or [] if _s(x)]: out.append("CATEGORIES:" + ",".join(categories)) if changed := _s(c.get("lastModifiedDateTime")): out.append(f"REV:{changed}") if uid := _s(c.get("id")): out.append(f"UID:{_text(uid)}") out.append("END:VCARD") return out
def _s(value: Any) -> str: return str(value).strip() if value is not None else "" def _text(value: str) -> str: """Escape a text value: backslash, comma, semicolon and line breaks.""" value = value.replace("\\", "\\\\").replace(",", "\\,").replace(";", "\\;") return value.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\\n") def _fold(line: str) -> str: """Fold a line at 75 octets, without splitting a UTF-8 character.""" out, current, size = [], "", 0 for ch in line: n = len(ch.encode()) if size + n > FOLD_AT: out.append(current) current, size = " ", 1 current += ch size += n out.append(current) return "\r\n".join(out)