nextcloud-client 0.211.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1321 @@
1
+ """CardDAV client for NextCloud contacts operations."""
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ import traceback
7
+ import xml.etree.ElementTree as ET
8
+ from datetime import date
9
+ from typing import Any
10
+
11
+ from pythonvCard4.vcard import Contact, escape_text, fold_line, unfold_lines
12
+
13
+ from .base import BaseNextcloudClient
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ # Canonical keys accepted by _build_contact_from_data. Callers normalise aliases
19
+ # (``phone``→``tel``, ``organization``→``org``, ``address``→``adr``) via
20
+ # _normalize_contact_data beforehand
21
+ # so the set never needs to list them.
22
+ _SUPPORTED_CONTACT_KEYS = frozenset(
23
+ {
24
+ "fn",
25
+ "n",
26
+ "email",
27
+ "tel",
28
+ "org",
29
+ "note",
30
+ "title",
31
+ "nickname",
32
+ "bday",
33
+ "categories",
34
+ "url",
35
+ "adr",
36
+ }
37
+ )
38
+
39
+ # vCard ADR components, in RFC 6350 §6.3.1 order.
40
+ _ADR_COMPONENTS = (
41
+ "po_box",
42
+ "extended",
43
+ "street",
44
+ "locality",
45
+ "region",
46
+ "postal_code",
47
+ "country",
48
+ )
49
+ _PARAM_TOKEN = re.compile(r"[A-Za-z0-9-]+")
50
+
51
+
52
+ def _adr_entries(value: Any) -> list[dict[str, Any]]:
53
+ """Normalise ``adr`` input into pythonvCard4's ``[{value, type}]`` shape.
54
+
55
+ Accepts a dict keyed by ``_ADR_COMPONENTS`` plus an optional ``type`` (str or
56
+ list), a raw ``"pobox;ext;street;locality;region;code;country"`` string
57
+ (split on ``;`` as-is, like ``n``, so a component containing ``;`` or ``,``
58
+ needs the dict form), or a list of either. Entries with no
59
+ non-empty component are dropped. ``type`` is omitted when not given.
60
+ """
61
+ if value is None:
62
+ return []
63
+ items = value if isinstance(value, list) else [value]
64
+ return [e for e in map(_adr_entry, items) if e is not None]
65
+
66
+
67
+ def _adr_entry(item: Any) -> dict[str, Any] | None:
68
+ """One ``adr`` item to ``{value, type}``; ``None`` (logged) if unusable."""
69
+ types: Any = None
70
+ if isinstance(item, str):
71
+ comps = item.split(";")
72
+ if len(comps) > len(_ADR_COMPONENTS):
73
+ # Shape only: address values are personal data.
74
+ logger.warning("Truncating ADR string from %d to 7 components", len(comps))
75
+ elif isinstance(item, dict):
76
+ if unknown := set(item) - {*_ADR_COMPONENTS, "type"}:
77
+ logger.warning("Ignoring unknown ADR keys: %s", sorted(unknown))
78
+ comps = [_name_component_str(item.get(k) or "") for k in _ADR_COMPONENTS]
79
+ types = item.get("type")
80
+ else:
81
+ logger.warning(
82
+ "Ignoring ADR entry that is not a dict or str: %s", type(item).__name__
83
+ )
84
+ return None
85
+ # Normalise CR here: pythonvCard4's escape_text (create path) escapes
86
+ # only LF, so a bare CR was written raw and lost on read.
87
+ comps = [c.replace("\r\n", "\n").replace("\r", "\n") for c in comps]
88
+ comps = (comps + [""] * len(_ADR_COMPONENTS))[: len(_ADR_COMPONENTS)]
89
+ if not any(c.strip() for c in comps):
90
+ return None
91
+ entry: dict[str, Any] = {"value": comps}
92
+ if safe := _safe_param_tokens(types):
93
+ entry["type"] = safe
94
+ return entry
95
+
96
+
97
+ def _safe_param_tokens(types: Any) -> list[str]:
98
+ """Keep only RFC 6350 param tokens, logging the rest.
99
+
100
+ TYPE lands unescaped in the property head on both write paths, so a value
101
+ like ``"work\\nEMAIL:x"`` would otherwise inject a line.
102
+ """
103
+ if types is None:
104
+ return []
105
+ # Only a str or a list/tuple is a TYPE value; anything else (5, True, a
106
+ # dict, which would iterate its keys) is one rejected value, not a crash.
107
+ candidates = list(types) if isinstance(types, (list, tuple)) else [types]
108
+ safe: list[str] = []
109
+ rejected: list[Any] = []
110
+ for t in candidates:
111
+ if isinstance(t, str) and _PARAM_TOKEN.fullmatch(t):
112
+ safe.append(t)
113
+ else:
114
+ rejected.append(t)
115
+ if rejected:
116
+ # Count only: a rejected value is arbitrary caller input.
117
+ logger.warning("Ignoring %d invalid ADR type value(s)", len(rejected))
118
+ return safe
119
+
120
+
121
+ def _adr_line(entry: dict[str, Any]) -> str:
122
+ params = f";TYPE={','.join(entry['type'])}" if entry.get("type") else ""
123
+ comps = ";".join(_escape_n_component(c) for c in entry["value"])
124
+ return f"ADR{params}:{comps}"
125
+
126
+
127
+ # vCard N components, in RFC 6350 §6.2.2 order.
128
+ _N_COMPONENTS = (
129
+ "family_name",
130
+ "given_name",
131
+ "additional_names",
132
+ "honorific_prefix",
133
+ "honorific_suffix",
134
+ )
135
+
136
+
137
+ def _pop_name_parts(data: dict[str, Any]) -> dict[str, str]:
138
+ """Pop structured-name input from ``data`` into ``{component: value}``.
139
+
140
+ Accepts the flat keys in ``_N_COMPONENTS`` and/or ``n`` as a dict with those
141
+ keys, a positional list, or a raw ``"Family;Given;Additional;Prefix;Suffix"``
142
+ string (split on ``;`` as-is, not unescaped — use the flat keys for a
143
+ component containing ``;``). Flat keys win over ``n``. Only components
144
+ actually supplied are returned, so an update can change one part and keep
145
+ the rest (issue #1749). ``None`` means "not supplied", not "clear it"; pass
146
+ ``""`` to clear a component.
147
+ """
148
+ raw = data.pop("n", None)
149
+ if isinstance(raw, str):
150
+ raw = raw.split(";") if raw.strip() else None
151
+ if isinstance(raw, list):
152
+ raw = dict(zip(_N_COMPONENTS, raw))
153
+ parts = (
154
+ {k: v for k, v in raw.items() if k in _N_COMPONENTS}
155
+ if isinstance(raw, dict)
156
+ else {}
157
+ )
158
+ for key in _N_COMPONENTS:
159
+ value = data.pop(key, None)
160
+ if value is not None:
161
+ parts[key] = value
162
+ return {k: _name_component_str(v) for k, v in parts.items() if v is not None}
163
+
164
+
165
+ def _name_component_str(value: Any) -> str:
166
+ """A list (e.g. several additional names) is space-joined."""
167
+ if isinstance(value, list):
168
+ return " ".join(str(v) for v in value if v)
169
+ return str(value)
170
+
171
+
172
+ def _fn_from_name_parts(parts: dict[str, str]) -> str:
173
+ """Derive a display name: prefix, given, additional, family, suffix."""
174
+ order = (
175
+ "honorific_prefix",
176
+ "given_name",
177
+ "additional_names",
178
+ "family_name",
179
+ "honorific_suffix",
180
+ )
181
+ return " ".join(parts[k] for k in order if parts.get(k))
182
+
183
+
184
+ def _escape_n_component(value: str) -> str:
185
+ return escape_text(value.replace("\r\n", "\n").replace("\r", "\n"))
186
+
187
+
188
+ def _split_unescaped(value: str, sep: str = ";") -> list[str]:
189
+ """Split a raw (still escaped) structured value on its unescaped ``sep``.
190
+
191
+ Escape pairs are consumed whole, so ``\\\\;`` -- an escaped backslash, then
192
+ a separator -- splits, while ``\\;`` does not. A ``(?<!\\);`` lookbehind
193
+ gets the first case wrong and shifts every later component one slot.
194
+ """
195
+ comps: list[str] = []
196
+ current: list[str] = []
197
+ chars = iter(value)
198
+ for char in chars:
199
+ if char == "\\":
200
+ current.append(char + next(chars, ""))
201
+ elif char == sep:
202
+ comps.append("".join(current))
203
+ current = []
204
+ else:
205
+ current.append(char)
206
+ comps.append("".join(current))
207
+ return comps
208
+
209
+
210
+ def _unescape_component(component: str) -> str:
211
+ """Single-pass vCard unescape (RFC 6350 §3.4).
212
+
213
+ ``pythonvCard4.unescape_text`` chains ``replace`` calls, so it decodes an
214
+ escaped backslash followed by ``n`` as a line break.
215
+ """
216
+ return re.sub(r"\\(.)", lambda m: "\n" if m[1] in "nN" else m[1], component)
217
+
218
+
219
+ def _merge_n_value(existing: str, parts: dict[str, str]) -> str:
220
+ """Overwrite the supplied components of an existing raw N value.
221
+
222
+ Existing components are split on unescaped ``;`` and kept verbatim (still
223
+ escaped); supplied components are escaped and written in their slot.
224
+ """
225
+ comps = _split_unescaped(existing) if existing else []
226
+ comps += [""] * (len(_N_COMPONENTS) - len(comps))
227
+ for i, key in enumerate(_N_COMPONENTS):
228
+ if key in parts:
229
+ comps[i] = _escape_n_component(parts[key])
230
+ return ";".join(comps)
231
+
232
+
233
+ def _normalize_contact_data(contact_data: dict[str, Any]) -> dict[str, Any]:
234
+ """Map documented aliases to canonical keys.
235
+
236
+ ``phone`` → ``tel``, ``organization`` → ``org``, ``address`` → ``adr``. A
237
+ ``None`` value counts as not supplied. The canonical key wins if both
238
+ are supplied, so callers who set ``tel`` don't lose it to a stray ``phone`` entry.
239
+ Structured-name keys (``given_name``, ``family_name``, …, or ``n``) collapse
240
+ into ``n`` as a ``{component: value}`` dict — see ``_pop_name_parts``.
241
+ Returns a new dict — does not mutate the caller's argument.
242
+ """
243
+ normalised = dict(contact_data)
244
+ name_parts = _pop_name_parts(normalised)
245
+ if name_parts:
246
+ normalised["n"] = name_parts
247
+ for alias, canonical in (
248
+ ("phone", "tel"),
249
+ ("organization", "org"),
250
+ ("address", "adr"),
251
+ ):
252
+ # ``None`` = not supplied (as for name parts): an update keeps the
253
+ # property, and a ``None`` canonical key doesn't shadow its alias.
254
+ if normalised.get(canonical) is None:
255
+ normalised.pop(canonical, None)
256
+ if normalised.get(alias) is not None:
257
+ normalised[canonical] = normalised[alias]
258
+ normalised.pop(alias, None)
259
+ if "adr" in normalised:
260
+ # Parsed once here; both write paths consume ``adr`` as ready entries.
261
+ raw_adr = normalised["adr"]
262
+ normalised["adr"] = _adr_entries(raw_adr)
263
+ if raw_adr != [] and not normalised["adr"]:
264
+ # Only a literal ``[]`` clears addresses on update. Input that yields
265
+ # no entry (all empty, misspelled keys) is far likelier a mistake.
266
+ logger.warning(
267
+ "Ignoring adr with no usable address (%s)", type(raw_adr).__name__
268
+ )
269
+ del normalised["adr"]
270
+ unknown = set(normalised) - _SUPPORTED_CONTACT_KEYS
271
+ if unknown:
272
+ # Warning, not debug: a dropped key is otherwise invisible (GH #1814).
273
+ logger.warning("Ignoring unknown contact_data keys: %s", sorted(unknown))
274
+ for key in unknown:
275
+ del normalised[key]
276
+ return normalised
277
+
278
+
279
+ def _wrap_contact_field(
280
+ value: str | dict[str, Any] | list[str | dict[str, Any]] | None,
281
+ ) -> list[dict[str, Any]]:
282
+ """Normalize an email/tel input into pythonvCard4's list-of-dicts shape.
283
+
284
+ Accepts a plain string, a dict already in ``{value, type}`` form, or a list of
285
+ either. Empty strings and dicts without a ``value`` key are dropped. Always
286
+ returns a list (possibly empty).
287
+ """
288
+ if value is None or value == "":
289
+ return []
290
+ items = value if isinstance(value, list) else [value]
291
+ out: list[dict[str, Any]] = []
292
+ for item in items:
293
+ if isinstance(item, dict) and item.get("value"):
294
+ types = item.get("type") or ["HOME"]
295
+ # Wrap a bare string so ``list("WORK")`` doesn't iterate it into
296
+ # ``["W", "O", "R", "K"]`` — same char-iteration footgun this whole
297
+ # helper exists to avoid for the outer ``value``.
298
+ if isinstance(types, str):
299
+ types = [types]
300
+ out.append({"value": item["value"], "type": list(types)})
301
+ elif isinstance(item, str) and item:
302
+ out.append({"value": item, "type": ["HOME"]})
303
+ return out
304
+
305
+
306
+ def _as_str_list(value: str | list[str]) -> list[str]:
307
+ """Wrap a bare string in a list. Does NOT split on commas.
308
+
309
+ Used for ORG/NICKNAME/URL where commas are part of the value (e.g.
310
+ ``"Smith, Jones & Associates"``) and only the list wrapper is needed to
311
+ prevent pythonvCard4 from iterating the string character-by-character.
312
+ """
313
+ return value if isinstance(value, list) else [value]
314
+
315
+
316
+ def _split_categories(value: str | list[str]) -> list[str]:
317
+ """Normalise CATEGORIES input: a comma-separated string is split into a list.
318
+
319
+ Unlike ORG/NICKNAME, CATEGORIES is canonically comma-separated in vCards
320
+ (``CATEGORIES:a,b,c``) so splitting a bare string is the expected shape.
321
+ Lists pass through unchanged — callers that already provide ``["a,b"]`` keep
322
+ their exact item, no double-splitting.
323
+ """
324
+ if isinstance(value, list):
325
+ return value
326
+ return [item.strip() for item in value.split(",") if item.strip()]
327
+
328
+
329
+ def _parse_bday(value: str | date | None) -> date | None:
330
+ """Parse a BDAY input to a ``date``. Logs and returns ``None`` if unparseable.
331
+
332
+ Shared by the create path (``_build_contact_from_data``) and the update path
333
+ (``_merge_vcard_properties``) so a non-ISO BDAY is rejected consistently
334
+ instead of being written raw on update.
335
+ """
336
+ if value is None or value == "":
337
+ return None
338
+ if isinstance(value, date):
339
+ return value
340
+ if isinstance(value, str):
341
+ try:
342
+ return date.fromisoformat(value)
343
+ except ValueError:
344
+ # Not the value itself: a birthday is personal data.
345
+ logger.warning("Ignoring non-ISO bday value (expected YYYY-MM-DD)")
346
+ return None
347
+
348
+
349
+ def _first_custom(custom: dict[str, str | list[str]], key: str) -> str | None:
350
+ """Return the first raw value pythonvCard4 stashed in ``custom[key]``.
351
+
352
+ The library has no typed parser for ORG / TITLE / unencoded PHOTO, so they
353
+ end up in ``Contact.custom`` keyed by property name. The library's typeshed
354
+ declares the values as ``str | list[str]`` even though the current parser
355
+ always appends to a list — accept both shapes so we don't break on a future
356
+ library version that switches to bare strings. Returns ``None`` when the
357
+ key is absent or the value is empty.
358
+ """
359
+ values = custom.get(key)
360
+ if isinstance(values, list):
361
+ return values[0] if values else None
362
+ if isinstance(values, str):
363
+ return values or None
364
+ return None
365
+
366
+
367
+ def _split_property_head(line: str) -> tuple[str, str]:
368
+ """Split a logical vCard line into its group prefix and upper-cased name.
369
+
370
+ ``FN:Alice`` -> ``("", "FN")``
371
+ ``email;TYPE=WORK:a@b`` -> ``("", "EMAIL")``
372
+ ``item1.URL:https://x`` -> ``("item1.", "URL")``
373
+
374
+ Property names are case-insensitive per RFC 6350 §3.3, and Apple-produced
375
+ cards group related properties (``item1.URL`` + ``item1.X-ABLabel``). Matching
376
+ on the raw text missed both shapes, so a lower-cased ``fn:`` or a grouped
377
+ ``item1.EMAIL:`` was treated as unknown — preserved verbatim *and* then
378
+ duplicated by the add-new loop. The group prefix is returned so a rewritten
379
+ line can keep it and stay attached to its ``X-ABLabel``.
380
+ """
381
+ head = line.split(":", 1)[0].split(";", 1)[0]
382
+ group, sep, name = head.rpartition(".")
383
+ return group + sep, name.upper()
384
+
385
+
386
+ def _existing_parameters(line: str) -> str:
387
+ """Return a logical line's parameter section verbatim, including the leading ``;``.
388
+
389
+ ``EMAIL;PREF=1;TYPE=work:a@b`` -> ``";PREF=1;TYPE=work"``
390
+ ``item1.EMAIL:a@b`` -> ``""``
391
+
392
+ Copying the whole section rather than re-deriving a single ``TYPE=`` value
393
+ preserves *every* parameter on a rewritten line. The previous approach
394
+ reconstructed the line as ``EMAIL;TYPE=<value>:``, which silently dropped any
395
+ other parameter — ``PREF``, ``X-ABLabel``, ``CHARSET`` — and dropped ``TYPE``
396
+ itself whenever it was not the parameter being matched. Verbatim copying also
397
+ sidesteps casing entirely: no case-insensitive search, so no dependence on
398
+ ``str.upper()`` being length-preserving (it isn't — ``"ß".upper() == "SS"``).
399
+
400
+ Known limitation, unchanged from the original: the value separator is taken
401
+ as the first ``:``, so a quoted parameter value containing a colon
402
+ (``TYPE="a:b"``, legal per RFC 6350 §3.3) would split early. No producer we
403
+ have seen emits one.
404
+ """
405
+ head, separator, _ = line.partition(":")
406
+ if not separator:
407
+ return ""
408
+ param_start = head.find(";")
409
+ return head[param_start:] if param_start != -1 else ""
410
+
411
+
412
+ # Properties pythonvCard4 stashes in ``Contact.custom`` that the projection
413
+ # already surfaces under their own key. Everything else in ``custom`` is a
414
+ # genuine extension (``X-*``) and is passed through. PHOTO is excluded
415
+ # deliberately: it is already returned as ``photo``, and re-emitting a base64
416
+ # image per contact would roughly double every list_contacts response.
417
+ _CUSTOM_KEYS_ALREADY_SURFACED = frozenset({"FN", "N", "ORG", "TITLE", "PHOTO"})
418
+
419
+
420
+ def _custom_extras(custom: dict[str, str | list[str]]) -> dict[str, str | list[str]]:
421
+ """Return the ``X-*`` extensions from ``Contact.custom``, minus duplicates."""
422
+ return {
423
+ key: value
424
+ for key, value in custom.items()
425
+ if key.upper() not in _CUSTOM_KEYS_ALREADY_SURFACED
426
+ }
427
+
428
+
429
+ def _exc_summary(exc: BaseException) -> str:
430
+ """Exception class and raising frame, without the message.
431
+
432
+ Contact data is personal data and must not reach the logs. pythonvCard4's
433
+ parse errors carry the offending value in their message (``date.fromisoformat``
434
+ -> ``Invalid isoformat string: '<the birthday>'``), so log handlers around
435
+ vCard parsing use this instead of ``exc_info=True``.
436
+ """
437
+ frames = traceback.extract_tb(exc.__traceback__)
438
+ last = frames[-1] if frames else None
439
+ where = f" at {os.path.basename(last.filename)}:{last.lineno}" if last else ""
440
+ return f"{type(exc).__name__}{where}"
441
+
442
+
443
+ def _parses_alone(line: str) -> bool:
444
+ # Relies on from_vcard ignoring BEGIN/END/VERSION and taking the first FN,
445
+ # so structural lines probe clean. If a future release validates the
446
+ # envelope, every line "fails", the retry raises, and callers fall back to
447
+ # the pre-#1551 empty projection — degraded, never crashed.
448
+ try:
449
+ Contact.from_vcard(f"FN:x\n{line}")
450
+ except Exception:
451
+ return False
452
+ return True
453
+
454
+
455
+ def _parse_vcard(vcard_text: str) -> Contact:
456
+ """Parse a vCard, dropping only the properties pythonvCard4 chokes on.
457
+
458
+ The library raises on shapes real servers store — a reduced-form
459
+ ``BDAY:--1226`` (issue #1551), a vCard 3.0 ``GEO:lat,lon`` — and a raise
460
+ loses every field of the contact. On failure, retry without the lines that
461
+ fail in isolation, so the contact keeps its name, phone and email.
462
+ """
463
+ lines = unfold_lines(vcard_text.splitlines())
464
+ try:
465
+ contact = Contact.from_vcard(vcard_text)
466
+ except Exception:
467
+ dropped = [line for line in lines if not _parses_alone(line)]
468
+ if not dropped:
469
+ raise
470
+ logger.warning(
471
+ "Dropped unparseable vCard properties: %s",
472
+ [line.split(":", 1)[0] for line in dropped],
473
+ )
474
+ lines = [line for line in lines if line not in dropped]
475
+ contact = Contact.from_vcard("\n".join(lines))
476
+ _resplit_structured(contact, lines)
477
+ return contact
478
+
479
+
480
+ #: Structured properties pythonvCard4 splits, and the separator it splits on.
481
+ #: NICKNAME is ``,``-separated in RFC 6350; ``;`` matches what the library writes.
482
+ _STRUCTURED_SEPARATORS = {"N": ";", "ADR": ";", "NICKNAME": ";", "CATEGORIES": ","}
483
+
484
+
485
+ def _resplit_structured(contact: Contact, lines: list[str]) -> None:
486
+ """Re-split N, ADR, NICKNAME and CATEGORIES from their raw lines.
487
+
488
+ ponytail: workaround for pythonvCard4 <= 0.2.0, whose ``from_vcard``
489
+ unescapes these values *before* splitting them, so an escaped separator
490
+ inside one component (``N:Doe\\;Jr;John``) splits it and shifts every later
491
+ field. Remove this, and its call in ``_parse_vcard``, once a pythonvCard4
492
+ release ships https://github.com/sharf-shawon/pythonvCard4/pull/6, and raise
493
+ the dependency floor to that release.
494
+
495
+ Mirrors which line the library keeps: the first N, the last NICKNAME and
496
+ CATEGORIES, and every ADR in order, so ``contact.adr`` keeps its TYPEs.
497
+ """
498
+ adr_entries = iter(contact.adr)
499
+ n_done = False
500
+ for line in lines:
501
+ key, colon, raw = line.partition(":")
502
+ name = key.split(";", 1)[0].upper()
503
+ sep = _STRUCTURED_SEPARATORS.get(name)
504
+ if not colon or sep is None:
505
+ continue
506
+ comps = [_unescape_component(c) for c in _split_unescaped(raw, sep)]
507
+ if name == "N" and not n_done:
508
+ contact.n, n_done = comps, True
509
+ elif name == "ADR":
510
+ entry = next(adr_entries, None)
511
+ if entry is not None:
512
+ entry["value"] = comps
513
+ elif name == "NICKNAME":
514
+ contact.nickname = comps
515
+ elif name == "CATEGORIES":
516
+ contact.categories = comps
517
+
518
+
519
+ def _project_contact(contact: Contact) -> dict[str, Any]:
520
+ """Project a parsed vCard into the flat dict the server layer maps to a model.
521
+
522
+ Single projection point shared by ``list_contacts`` and ``update_contact`` so
523
+ the read-after-write shape cannot drift from the read shape.
524
+
525
+ pythonvCard4's parser has no branch for ORG / TITLE — they fall through into
526
+ ``contact.custom`` as a list of raw values. PHOTO only gets typed-parsed when
527
+ the line carries an ``ENCODING=`` parameter; otherwise it lands in ``custom``
528
+ too. Pull them out here so the read side surfaces what the write side
529
+ persisted (issue #716 follow-up).
530
+ """
531
+ return {
532
+ "fullname": contact.fn,
533
+ "nickname": contact.nickname,
534
+ "birthday": contact.bday.isoformat()
535
+ if isinstance(contact.bday, date)
536
+ else contact.bday,
537
+ "email": contact.email,
538
+ "tel": contact.tel,
539
+ "org": _first_custom(contact.custom, "ORG"),
540
+ "title": _first_custom(contact.custom, "TITLE"),
541
+ "note": contact.note,
542
+ "url": contact.url,
543
+ "categories": contact.categories,
544
+ "photo": contact.photo_data or _first_custom(contact.custom, "PHOTO"),
545
+ # ADR and N are parsed by the library but were never projected, so the
546
+ # model's ``addresses`` list was declared and permanently empty and
547
+ # ``given_name``/``family_name`` were never populated.
548
+ "adr": contact.adr,
549
+ "n": contact.n,
550
+ "custom": _custom_extras(contact.custom),
551
+ }
552
+
553
+
554
+ def _safe_vcard_value(value: Any) -> Any:
555
+ """Escape newlines in a value so it can't inject additional vCard properties.
556
+
557
+ Per RFC 6350 §3.4 newlines inside a property value are encoded as ``\\n``.
558
+ Unfolding this on the read side is pythonvCard4's job; we only need to make
559
+ sure ``contact_data`` strings don't terminate the line on the way out.
560
+ """
561
+ if isinstance(value, str):
562
+ return value.replace("\r\n", "\\n").replace("\n", "\\n").replace("\r", "\\n")
563
+ return value
564
+
565
+
566
+ def _build_contact_from_data(contact_data: dict[str, Any], uid: str) -> Contact:
567
+ """Build a pythonvCard4 Contact from an MCP ``contact_data`` dict.
568
+
569
+ Maps every key documented on ``nc_contacts_create_contact`` onto the underlying
570
+ library, normalising shapes (list/str) to avoid pythonvCard4's char-by-char
571
+ iteration of bare strings — see issue #716.
572
+
573
+ Callers must pre-normalise aliases via ``_normalize_contact_data`` before
574
+ invoking this helper; it assumes canonical keys only.
575
+ """
576
+ data = contact_data
577
+ name_parts = data.get("n") or {}
578
+ fn = data.get("fn") or _fn_from_name_parts(name_parts)
579
+
580
+ if not fn:
581
+ logger.warning(
582
+ "contact_data missing required 'fn' field; pythonvCard4 may reject or "
583
+ "produce an invalid vCard"
584
+ )
585
+
586
+ # N is always written (empty components when none were given): vCard 3.0
587
+ # requires it and clients sort by it. No splitting of ``fn`` — that guesses
588
+ # wrong on titles and particles ("Dr. Jane van Doe"), see issue #1749.
589
+ kwargs: dict[str, Any] = {
590
+ "fn": fn,
591
+ "uid": uid,
592
+ "n": [name_parts.get(k, "") for k in _N_COMPONENTS],
593
+ }
594
+
595
+ emails = _wrap_contact_field(data.get("email"))
596
+ if emails:
597
+ kwargs["email"] = emails
598
+
599
+ tels = _wrap_contact_field(data.get("tel"))
600
+ if tels:
601
+ kwargs["tel"] = tels
602
+
603
+ if data.get("org"):
604
+ kwargs["org"] = _as_str_list(data["org"])
605
+
606
+ if data.get("note"):
607
+ kwargs["note"] = data["note"]
608
+
609
+ if data.get("title"):
610
+ kwargs["title"] = data["title"]
611
+
612
+ if data.get("nickname"):
613
+ kwargs["nickname"] = _as_str_list(data["nickname"])
614
+
615
+ if data.get("categories"):
616
+ kwargs["categories"] = _split_categories(data["categories"])
617
+
618
+ if data.get("url"):
619
+ kwargs["url"] = _as_str_list(data["url"])
620
+
621
+ bday = _parse_bday(data.get("bday"))
622
+ if bday is not None:
623
+ kwargs["bday"] = bday
624
+
625
+ if data.get("adr"):
626
+ kwargs["adr"] = data["adr"] # already entries, see _normalize_contact_data
627
+
628
+ # kwargs built dynamically from contact_data; pythonvCard4's Contact typeshed
629
+ # has specific typed params and doesn't accept **dict[str, Any].
630
+ return Contact(**kwargs) # type: ignore[arg-type]
631
+
632
+
633
+ class ContactsClient(BaseNextcloudClient):
634
+ """Client for NextCloud CardDAV contact operations."""
635
+
636
+ app_name = "contacts"
637
+
638
+ def _get_carddav_base_path(self) -> str:
639
+ """Helper to get the base CardDAV path for contacts."""
640
+ return f"/remote.php/dav/addressbooks/users/{self._principal_or_username()}"
641
+
642
+ async def _list_object_names(self, addressbook: str) -> list[str]:
643
+ """Return the CardDAV object filenames stored in ``addressbook``.
644
+
645
+ A lightweight ``PROPFIND`` (Depth: 1, ``getetag`` only) over the
646
+ collection. The DAV object filename is independent of the vCard's
647
+ internal ``UID`` and is *not* guaranteed to be ``<uid>.vcf`` — see
648
+ issue #874 — so callers that need to address a specific object must
649
+ discover its real name rather than constructing one.
650
+ """
651
+ await self._ensure_principal_id()
652
+ carddav_path = self._get_carddav_base_path()
653
+ propfind_body = """<?xml version="1.0" encoding="utf-8"?>
654
+ <d:propfind xmlns:d="DAV:"><d:prop><d:getetag/></d:prop></d:propfind>"""
655
+ headers = {
656
+ "Depth": "1",
657
+ "Content-Type": "application/xml",
658
+ "Accept": "application/xml",
659
+ }
660
+ response = await self._make_request(
661
+ "PROPFIND",
662
+ f"{carddav_path}/{addressbook}",
663
+ content=propfind_body,
664
+ headers=headers,
665
+ )
666
+
667
+ ns = {"d": "DAV:"}
668
+ root = ET.fromstring(response.content)
669
+ names: list[str] = []
670
+ for response_elem in root.findall(".//d:response", ns):
671
+ href = response_elem.find(".//d:href", ns)
672
+ if href is None or not href.text:
673
+ continue
674
+ # The collection itself is reported with a trailing slash; skip it
675
+ # so only contact objects remain. The guard means href.text never
676
+ # ends with "/" below, so the bare split is sufficient.
677
+ if href.text.endswith("/"):
678
+ continue
679
+ names.append(href.text.split("/")[-1])
680
+ return names
681
+
682
+ async def _resolve_object_name(self, addressbook: str, uid: str) -> str | None:
683
+ """Map a surfaced contact id back to its real CardDAV object filename.
684
+
685
+ ``list_contacts`` surfaces ``vcard_id`` with a trailing ``.vcf`` suffix
686
+ stripped, so reverse that transform here: return the object whose
687
+ filename reduces to ``uid``. The conventional ``<uid>.vcf`` is
688
+ preferred when present (deterministic for the common case), otherwise
689
+ the first matching name is returned. ``None`` when no object matches.
690
+ """
691
+ candidates = [
692
+ name
693
+ for name in await self._list_object_names(addressbook)
694
+ if name.removesuffix(".vcf") == uid
695
+ ]
696
+ if not candidates:
697
+ return None
698
+ conventional = f"{uid}.vcf"
699
+ return conventional if conventional in candidates else candidates[0]
700
+
701
+ async def list_addressbooks(self):
702
+ """List all available addressbooks for the user."""
703
+
704
+ await self._ensure_principal_id()
705
+ carddav_path = self._get_carddav_base_path()
706
+
707
+ propfind_body = """<?xml version="1.0" encoding="utf-8"?>
708
+ <d:propfind xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/">
709
+ <d:prop>
710
+ <d:displayname/>
711
+ <d:getctag />
712
+ </d:prop>
713
+ </d:propfind>"""
714
+
715
+ headers = {
716
+ # "Depth": "0",
717
+ "Content-Type": "application/xml",
718
+ "Accept": "application/xml",
719
+ }
720
+
721
+ response = await self._make_request(
722
+ "PROPFIND", carddav_path, content=propfind_body, headers=headers
723
+ )
724
+
725
+ ns = {"d": "DAV:"}
726
+
727
+ # logger.info(response.content)
728
+ root = ET.fromstring(response.content)
729
+ addressbooks = []
730
+ for response_elem in root.findall(".//d:response", ns):
731
+ href = response_elem.find(".//d:href", ns)
732
+ if href is None:
733
+ continue
734
+
735
+ href_text = href.text or ""
736
+ if not href_text.endswith("/"):
737
+ continue # Skip non-addressbook resources
738
+
739
+ # Extract addressbook name from href
740
+ addressbook_name = href_text.rstrip("/").split("/")[-1]
741
+ if (
742
+ not addressbook_name
743
+ or addressbook_name == self._principal_or_username()
744
+ ):
745
+ continue
746
+
747
+ # Get properties
748
+ propstat = response_elem.find(".//d:propstat", ns)
749
+ if propstat is None:
750
+ continue
751
+
752
+ prop = propstat.find(".//d:prop", ns)
753
+ if prop is None:
754
+ continue
755
+
756
+ displayname_elem = prop.find(".//d:displayname", ns)
757
+ displayname = (
758
+ displayname_elem.text
759
+ if displayname_elem is not None
760
+ else addressbook_name
761
+ )
762
+
763
+ getctag_elem = prop.find(".//d:getctag", ns)
764
+ getctag = getctag_elem.text if getctag_elem is not None else None
765
+
766
+ addressbooks.append(
767
+ {
768
+ "name": addressbook_name,
769
+ "display_name": displayname,
770
+ "getctag": getctag,
771
+ }
772
+ )
773
+
774
+ logger.debug("Found %s addressbooks", len(addressbooks))
775
+ return addressbooks
776
+
777
+ async def create_addressbook(self, *, name: str, display_name: str):
778
+ """Create a new addressbook."""
779
+ await self._ensure_principal_id()
780
+ carddav_path = self._get_carddav_base_path()
781
+ url = f"{carddav_path}/{name}/"
782
+
783
+ prop_body = f"""<?xml version="1.0" encoding="utf-8"?>
784
+ <d:mkcol xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
785
+ <d:set>
786
+ <d:prop>
787
+ <d:resourcetype>
788
+ <d:collection/>
789
+ <c:addressbook/>
790
+ </d:resourcetype>
791
+ <d:displayname>{display_name}</d:displayname>
792
+ </d:prop>
793
+ </d:set>
794
+ </d:mkcol>"""
795
+
796
+ headers = {
797
+ "Content-Type": "application/xml",
798
+ }
799
+
800
+ await self._make_request("MKCOL", url, content=prop_body, headers=headers)
801
+
802
+ async def delete_addressbook(self, *, name: str):
803
+ """Delete an addressbook."""
804
+ await self._ensure_principal_id()
805
+ carddav_path = self._get_carddav_base_path()
806
+ url = f"{carddav_path}/{name}/"
807
+ await self._make_request("DELETE", url)
808
+
809
+ async def create_contact(
810
+ self, *, addressbook: str, uid: str, contact_data: dict[str, Any]
811
+ ):
812
+ """Create a new contact."""
813
+ await self._ensure_principal_id()
814
+ carddav_path = self._get_carddav_base_path()
815
+ url = f"{carddav_path}/{addressbook}/{uid}.vcf"
816
+
817
+ # Normalise aliases here so the helper's invariant (canonical keys only) holds.
818
+ contact_data = _normalize_contact_data(contact_data)
819
+ vcard = _build_contact_from_data(contact_data, uid).to_vcard()
820
+
821
+ headers = {
822
+ "Content-Type": "text/vcard; charset=utf-8",
823
+ "If-None-Match": "*",
824
+ }
825
+
826
+ await self._make_request("PUT", url, content=vcard, headers=headers)
827
+
828
+ async def delete_contact(self, *, addressbook: str, uid: str):
829
+ """Delete a contact regardless of its CardDAV object filename.
830
+
831
+ The object filename is independent of the vCard ``UID`` and may lack a
832
+ ``.vcf`` extension (e.g. the stock ``default`` sample contact), so the
833
+ real object name is resolved before deleting rather than assuming
834
+ ``<uid>.vcf`` (issue #874). Falls back to the conventional name when no
835
+ object matches so a genuinely missing contact still surfaces a 404.
836
+ """
837
+ await self._ensure_principal_id()
838
+ carddav_path = self._get_carddav_base_path()
839
+ object_name = await self._resolve_object_name(addressbook, uid) or f"{uid}.vcf"
840
+ url = f"{carddav_path}/{addressbook}/{object_name}"
841
+ await self._make_request("DELETE", url)
842
+
843
+ async def update_contact(
844
+ self,
845
+ *,
846
+ addressbook: str,
847
+ uid: str,
848
+ contact_data: dict[str, Any],
849
+ etag: str = "",
850
+ ) -> dict[str, Any]:
851
+ """Update an existing contact while preserving all existing properties.
852
+
853
+ The existing vCard is **always** fetched and merged into. Previously the
854
+ fetch was skipped whenever the caller supplied an ``etag``, so the
855
+ concurrency-correct call silently fell through to a rebuild from the
856
+ handful of supported keys — destroying PHOTO, ADR, N, X-*, IMPP, GEO and
857
+ REV. There is no rebuild path any more: if the existing card cannot be
858
+ read, this raises rather than replacing it with a synthesised one.
859
+
860
+ Returns the same shape as one ``list_contacts`` entry, carrying the new
861
+ ETag so callers can chain updates without a re-read. ``getetag`` is an
862
+ empty string when the server omitted the header from the PUT response
863
+ (some proxies strip it); chaining then requires a fresh read first.
864
+
865
+ Failures before the PUT raise. Failures *after* it do not: once the write
866
+ has landed, an error building the response projection would misreport a
867
+ successful update, so ``contact`` degrades to ``{}`` and the raw
868
+ ``addressdata`` plus the new ETag are still returned.
869
+ """
870
+ await self._ensure_principal_id()
871
+ carddav_path = self._get_carddav_base_path()
872
+ # Resolve the real object filename (may differ from ``<uid>.vcf``) so the
873
+ # GET and the PUT target the same resource — see issue #874.
874
+ object_name = await self._resolve_object_name(addressbook, uid) or f"{uid}.vcf"
875
+ url = f"{carddav_path}/{addressbook}/{object_name}"
876
+
877
+ contact_data = _normalize_contact_data(contact_data)
878
+
879
+ # Always read the current card: it is the only source of the properties
880
+ # this method has no vocabulary for. A failure here propagates — a raised
881
+ # error is recoverable, a silent rebuild is not.
882
+ raw_vcard_content, current_etag = await self._fetch_raw_vcard(
883
+ addressbook, object_name
884
+ )
885
+ # The caller's etag wins: it is their concurrency assertion, and honouring
886
+ # the freshly-read one instead would defeat the check they asked for.
887
+ if not etag:
888
+ etag = current_etag
889
+
890
+ vcard_content = self._merge_vcard_properties(raw_vcard_content, contact_data)
891
+
892
+ headers = {
893
+ "Content-Type": "text/vcard; charset=utf-8",
894
+ }
895
+ if etag:
896
+ headers["If-Match"] = etag
897
+
898
+ response = await self._make_request(
899
+ "PUT", url, content=vcard_content, headers=headers
900
+ )
901
+
902
+ # Re-parse the card we just wrote rather than issuing a second GET.
903
+ #
904
+ # Deliberately fail-open, unlike every other error path in this method:
905
+ # the PUT has already landed, so raising here would report a *successful*
906
+ # write as a failure and invite a pointless — possibly destructive —
907
+ # retry. The contract this method exists to protect ("never silently lose
908
+ # data") is already satisfied at this point; only the convenience
909
+ # projection is at risk. The caller still gets the new ETag and the full
910
+ # ``addressdata``, so nothing is withheld.
911
+ try:
912
+ contact_projection = _project_contact(_parse_vcard(vcard_content))
913
+ except Exception as exc:
914
+ # Broad by intent: pythonvCard4 is third-party and its parse failure
915
+ # modes aren't enumerable. Whatever it raises, the write stands.
916
+ # _exc_summary, not logger.exception: the message carries card data.
917
+ # Warning, not error: the write itself succeeded.
918
+ logger.warning(
919
+ "Contact %s was updated successfully but the written vCard could "
920
+ "not be re-parsed for the response projection (%s); returning the "
921
+ "raw card and ETag instead",
922
+ uid,
923
+ _exc_summary(exc),
924
+ )
925
+ contact_projection = {}
926
+
927
+ return {
928
+ "vcard_id": object_name.removesuffix(".vcf"),
929
+ "object_path": url,
930
+ "object_name": object_name,
931
+ "getetag": response.headers.get("etag", ""),
932
+ "contact": contact_projection,
933
+ "addressdata": vcard_content,
934
+ }
935
+
936
+ async def list_contacts(self, *, addressbook: str):
937
+ """List all available contacts for addressbook."""
938
+
939
+ await self._ensure_principal_id()
940
+ carddav_path = self._get_carddav_base_path()
941
+
942
+ report_body = """<?xml version="1.0" encoding="utf-8"?>
943
+ <card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
944
+ <d:prop>
945
+ <d:getetag />
946
+ <card:address-data />
947
+ </d:prop>
948
+ </card:addressbook-query>"""
949
+
950
+ headers = {
951
+ "Depth": "1",
952
+ "Content-Type": "application/xml",
953
+ "Accept": "application/xml",
954
+ }
955
+
956
+ response = await self._make_request(
957
+ "REPORT",
958
+ f"{carddav_path}/{addressbook}",
959
+ content=report_body,
960
+ headers=headers,
961
+ )
962
+
963
+ ns = {"d": "DAV:", "card": "urn:ietf:params:xml:ns:carddav"}
964
+
965
+ # logger.info(response.text)
966
+ root = ET.fromstring(response.content)
967
+ contacts = []
968
+ for response_elem in root.findall(".//d:response", ns):
969
+ href = response_elem.find(".//d:href", ns)
970
+ if href is None:
971
+ logger.info("Skip missing href")
972
+ continue
973
+
974
+ href_text = href.text or ""
975
+ # logger.info("Href text: %s", href_text)
976
+ # if not href_text.endswith("/"):
977
+ # logger.info("# Skip non-addressbook resources")
978
+ # continue
979
+
980
+ # The real CardDAV object: its full DAV path and bare filename. The
981
+ # filename is independent of the vCard UID and may lack a ``.vcf``
982
+ # extension, so preserve it verbatim for callers that need to
983
+ # address the object reliably (issue #874).
984
+ object_path = href_text
985
+ object_name = href_text.rstrip("/").split("/")[-1]
986
+ if not object_name:
987
+ logger.info("Skip missing vcard_id")
988
+ continue
989
+ # ``vcard_id`` keeps the historical ``.vcf``-stripped form for
990
+ # backward compatibility with callers that use it as the contact id.
991
+ # Must use the same trailing-suffix strip as ``_resolve_object_name``
992
+ # so the surface-then-resolve round-trip stays lossless (issue #874).
993
+ vcard_id = object_name.removesuffix(".vcf")
994
+
995
+ # Get properties
996
+ propstat = response_elem.find(".//d:propstat", ns)
997
+ if propstat is None:
998
+ logger.info("Skip missing propstat")
999
+ continue
1000
+
1001
+ prop = propstat.find(".//d:prop", ns)
1002
+ if prop is None:
1003
+ logger.info("Skip missing prop")
1004
+ continue
1005
+
1006
+ getetag_elem = prop.find(".//d:getetag", ns)
1007
+ getetag = getetag_elem.text if getetag_elem is not None else None
1008
+
1009
+ addressdata_elem = prop.find(".//card:address-data", ns)
1010
+ addressdata = (
1011
+ addressdata_elem.text if addressdata_elem is not None else None
1012
+ )
1013
+ if addressdata is None:
1014
+ logger.info("Skip missing addressdata")
1015
+ continue
1016
+
1017
+ # Isolate the parse per contact. pythonvCard4 raises on shapes real
1018
+ # servers store — e.g. a vCard 3.0 ``GEO:lat,lon`` (RFC 2426 uses a
1019
+ # comma; the library splits on ";"). Unguarded, one such contact made
1020
+ # the entire addressbook unlistable. Degrade to the raw card instead:
1021
+ # ``addressdata`` still carries everything, so the caller loses the
1022
+ # parsed convenience fields for that one contact, not the listing.
1023
+ try:
1024
+ contact_projection = _project_contact(_parse_vcard(addressdata))
1025
+ except Exception as exc:
1026
+ # _exc_summary, not exc_info: the message carries card data.
1027
+ logger.warning(
1028
+ "Could not parse vCard for %s in addressbook %s (%s); returning "
1029
+ "it with raw addressdata only",
1030
+ object_name,
1031
+ addressbook,
1032
+ _exc_summary(exc),
1033
+ )
1034
+ contact_projection = {}
1035
+
1036
+ contacts.append(
1037
+ {
1038
+ "vcard_id": vcard_id,
1039
+ "object_path": object_path,
1040
+ "object_name": object_name,
1041
+ "getetag": getetag,
1042
+ "contact": contact_projection,
1043
+ "addressdata": addressdata,
1044
+ }
1045
+ )
1046
+
1047
+ logger.debug("Found %s contacts", len(contacts))
1048
+ return contacts
1049
+
1050
+ async def _fetch_raw_vcard(
1051
+ self, addressbook: str, object_name: str
1052
+ ) -> tuple[str, str]:
1053
+ """Fetch raw vCard content + etag for an already-resolved object name.
1054
+
1055
+ Callers that only have a surfaced ``uid`` (not the real object name)
1056
+ must resolve it first via ``_resolve_object_name`` — see issue #874.
1057
+ ``update_contact`` does exactly that and passes the resolved name here.
1058
+ """
1059
+ await self._ensure_principal_id()
1060
+ carddav_path = self._get_carddav_base_path()
1061
+ url = f"{carddav_path}/{addressbook}/{object_name}"
1062
+
1063
+ try:
1064
+ response = await self._make_request("GET", url)
1065
+ etag = response.headers.get("etag", "")
1066
+ return response.text, etag
1067
+ except Exception as e:
1068
+ logger.error("Error getting raw vCard for %s: %s", object_name, e)
1069
+ raise
1070
+
1071
+ def _merge_vcard_properties(
1072
+ self, raw_vcard: str, contact_data: dict[str, Any]
1073
+ ) -> str:
1074
+ """Merge new contact data into existing raw vCard while preserving all properties.
1075
+
1076
+ The card's own ``UID`` line is carried through from ``raw_vcard`` like any
1077
+ other unrecognised property, so no ``uid`` argument is needed. (One used to
1078
+ be required solely by the removed rebuild fallback.)
1079
+
1080
+ Limitation: dict / list-form ``email`` and ``tel`` inputs are not applied
1081
+ by this text-merge path. Existing EMAIL/TEL lines are preserved unchanged,
1082
+ and no new lines are written for the dict/list inputs. Pass plain strings
1083
+ to update EMAIL/TEL here, or recreate via ``create_contact`` for full
1084
+ multi-entry support with TYPE annotations.
1085
+
1086
+ Unrecognised properties are copied through verbatim, but a property this
1087
+ method *rewrites* is re-emitted with its name upper-cased — a lower-cased
1088
+ ``fn:`` comes back as ``FN:``. Property names are case-insensitive per
1089
+ RFC 6350 §3.3 so this is semantically identical, but it is a visible
1090
+ formatting change and the only place the "preserve exact formatting"
1091
+ intent above does not hold literally. Group prefixes and the whole
1092
+ parameter section are copied verbatim.
1093
+
1094
+ Raises on any merge failure rather than substituting a synthesised card.
1095
+ This function previously caught every exception and returned a four-line
1096
+ vCard built from ``fn``/``email``/``tel``, which silently destroyed PHOTO,
1097
+ ADR, N, X-* and every other property while reporting success. A raised
1098
+ error is recoverable; a silent rebuild is not.
1099
+ """
1100
+ # Surface dict/list email/tel up front rather than silently no-op in the
1101
+ # add-new loop below (where the isinstance(value, str) guard skips them).
1102
+ for _key in ("email", "tel"):
1103
+ _value = contact_data.get(_key)
1104
+ if _value is not None and not isinstance(_value, str):
1105
+ logger.warning(
1106
+ "update_contact: %s (a %s, dict/list shape) is not applied via "
1107
+ "the text-merge update path; existing %s lines are preserved "
1108
+ "unchanged. Use a plain string to update %s here, or recreate "
1109
+ "via create_contact for multi-entry support.",
1110
+ _key,
1111
+ type(_value).__name__, # not the value: it is personal data
1112
+ _key.upper(),
1113
+ _key.upper(),
1114
+ )
1115
+ # Instead of using pythonvCard4 which has formatting issues,
1116
+ # let's do a simple text-based merge to preserve exact formatting.
1117
+ #
1118
+ # Unfold first: RFC 6350 §3.2 continuation lines start with a single
1119
+ # space/tab and belong to the property above them. The previous code
1120
+ # split on "\n" and ``.strip()``ed each physical line, which stripped that
1121
+ # leading space and re-emitted the continuation as a standalone property —
1122
+ # corrupting every long NOTE/ADR and every base64 PHOTO on any update.
1123
+ # ``splitlines()`` also handles CRLF, which ``split("\n")`` left as a
1124
+ # trailing "\r" on every line.
1125
+ lines = unfold_lines(raw_vcard.strip().splitlines())
1126
+ updated_lines = []
1127
+
1128
+ # Track what we've updated to avoid duplicates
1129
+ updated_properties = set()
1130
+
1131
+ for line in lines:
1132
+ if not line.strip():
1133
+ continue
1134
+
1135
+ group_prefix, property_name = _split_property_head(line)
1136
+
1137
+ # Skip the END:VCARD line for now
1138
+ if property_name == "END":
1139
+ continue
1140
+
1141
+ # Handle updates for specific properties
1142
+ if property_name == "FN" and "fn" in contact_data:
1143
+ updated_lines.append(
1144
+ f"{group_prefix}FN:{_safe_vcard_value(contact_data['fn'])}"
1145
+ )
1146
+ updated_properties.add("fn")
1147
+ elif property_name == "N" and "n" in contact_data:
1148
+ if "n" not in updated_properties:
1149
+ merged_n = _merge_n_value(line.partition(":")[2], contact_data["n"])
1150
+ params = _existing_parameters(line)
1151
+ updated_lines.append(f"{group_prefix}N{params}:{merged_n}")
1152
+ updated_properties.add("n")
1153
+ else:
1154
+ # Malformed card with a second N: preserve it untouched.
1155
+ updated_lines.append(line)
1156
+ elif property_name == "EMAIL" and "email" in contact_data:
1157
+ # Replace first email with new one, preserve others
1158
+ if "email" not in updated_properties:
1159
+ if isinstance(contact_data["email"], str):
1160
+ email_value = _safe_vcard_value(contact_data["email"])
1161
+ # Try to preserve the original format as much as possible
1162
+ params = _existing_parameters(line)
1163
+ updated_lines.append(
1164
+ f"{group_prefix}EMAIL{params}:{email_value}"
1165
+ )
1166
+ updated_properties.add("email")
1167
+ else:
1168
+ # Dict / list inputs aren't translatable to a single
1169
+ # text-merge replacement; keep the original line so we
1170
+ # don't silently drop the contact's email.
1171
+ updated_lines.append(line)
1172
+ else:
1173
+ # Keep additional emails unchanged
1174
+ updated_lines.append(line)
1175
+ elif property_name == "TEL" and "tel" in contact_data:
1176
+ # Similar handling for phone numbers
1177
+ if "tel" not in updated_properties:
1178
+ if isinstance(contact_data["tel"], str):
1179
+ tel_value = _safe_vcard_value(contact_data["tel"])
1180
+ params = _existing_parameters(line)
1181
+ updated_lines.append(f"{group_prefix}TEL{params}:{tel_value}")
1182
+ updated_properties.add("tel")
1183
+ else:
1184
+ # Same reasoning as the EMAIL branch above: don't drop.
1185
+ updated_lines.append(line)
1186
+ else:
1187
+ # Keep additional phone numbers unchanged
1188
+ updated_lines.append(line)
1189
+ elif property_name == "NOTE" and "note" in contact_data:
1190
+ updated_lines.append(
1191
+ f"{group_prefix}NOTE:{_safe_vcard_value(contact_data['note'])}"
1192
+ )
1193
+ updated_properties.add("note")
1194
+ elif property_name == "NICKNAME" and "nickname" in contact_data:
1195
+ nickname_value = contact_data["nickname"]
1196
+ if isinstance(nickname_value, list):
1197
+ nickname_value = ",".join(nickname_value)
1198
+ updated_lines.append(
1199
+ f"{group_prefix}NICKNAME:{_safe_vcard_value(nickname_value)}"
1200
+ )
1201
+ updated_properties.add("nickname")
1202
+ elif property_name == "BDAY" and "bday" in contact_data:
1203
+ parsed_bday = _parse_bday(contact_data["bday"])
1204
+ if parsed_bday is not None:
1205
+ updated_lines.append(
1206
+ f"{group_prefix}BDAY:{parsed_bday.isoformat()}"
1207
+ )
1208
+ updated_properties.add("bday")
1209
+ else:
1210
+ # Invalid input — keep the existing BDAY rather than
1211
+ # writing a malformed line or silently dropping it.
1212
+ updated_lines.append(line)
1213
+ elif property_name == "CATEGORIES" and "categories" in contact_data:
1214
+ categories_value = contact_data["categories"]
1215
+ if isinstance(categories_value, list):
1216
+ categories_value = ",".join(categories_value)
1217
+ updated_lines.append(
1218
+ f"{group_prefix}CATEGORIES:{_safe_vcard_value(categories_value)}"
1219
+ )
1220
+ updated_properties.add("categories")
1221
+ elif property_name == "ORG" and "org" in contact_data:
1222
+ org_value = contact_data["org"]
1223
+ # ORG is structured (Company;Department;…) per RFC 6350 §6.6.4;
1224
+ # join list components with ';' so callers using the same shape
1225
+ # ``_build_contact_from_data`` accepts don't get a Python repr.
1226
+ if isinstance(org_value, list):
1227
+ org_value = ";".join(org_value)
1228
+ updated_lines.append(
1229
+ f"{group_prefix}ORG:{_safe_vcard_value(org_value)}"
1230
+ )
1231
+ updated_properties.add("org")
1232
+ elif property_name == "TITLE" and "title" in contact_data:
1233
+ updated_lines.append(
1234
+ f"{group_prefix}TITLE:{_safe_vcard_value(contact_data['title'])}"
1235
+ )
1236
+ updated_properties.add("title")
1237
+ elif property_name == "URL" and "url" in contact_data:
1238
+ if "url" not in updated_properties:
1239
+ url_value = contact_data["url"]
1240
+ # Only the first URL from a list is written; multi-URL
1241
+ # contacts are rare and this text merge doesn't attempt
1242
+ # position-stable mapping to existing URL lines.
1243
+ if isinstance(url_value, list):
1244
+ url_value = url_value[0] if url_value else ""
1245
+ if url_value:
1246
+ updated_lines.append(
1247
+ f"{group_prefix}URL:{_safe_vcard_value(url_value)}"
1248
+ )
1249
+ updated_properties.add("url")
1250
+ else:
1251
+ # Keep additional URLs unchanged
1252
+ updated_lines.append(line)
1253
+ elif property_name == "ADR" and "adr" in contact_data:
1254
+ # A supplied ``adr`` is the contact's full address set: emit it in
1255
+ # place of the first existing ADR and drop the rest.
1256
+ if "adr" not in updated_properties:
1257
+ updated_lines.extend(_adr_line(e) for e in contact_data["adr"])
1258
+ updated_properties.add("adr")
1259
+ else:
1260
+ # Keep all other properties unchanged (preserves all extended/custom fields)
1261
+ updated_lines.append(line)
1262
+
1263
+ # Add any new properties that weren't in the original vCard
1264
+ for key, value in contact_data.items():
1265
+ if key not in updated_properties:
1266
+ if key == "fn":
1267
+ updated_lines.append(f"FN:{_safe_vcard_value(value)}")
1268
+ elif key == "n":
1269
+ updated_lines.append(f"N:{_merge_n_value('', value)}")
1270
+ elif key == "email" and isinstance(value, str):
1271
+ updated_lines.append(f"EMAIL:{_safe_vcard_value(value)}")
1272
+ elif key == "tel" and isinstance(value, str):
1273
+ updated_lines.append(f"TEL:{_safe_vcard_value(value)}")
1274
+ elif key == "note":
1275
+ updated_lines.append(f"NOTE:{_safe_vcard_value(value)}")
1276
+ elif key == "nickname":
1277
+ nickname_value = (
1278
+ value if isinstance(value, str) else ",".join(value)
1279
+ )
1280
+ updated_lines.append(
1281
+ f"NICKNAME:{_safe_vcard_value(nickname_value)}"
1282
+ )
1283
+ elif key == "bday":
1284
+ parsed_bday = _parse_bday(value)
1285
+ if parsed_bday is not None:
1286
+ updated_lines.append(f"BDAY:{parsed_bday.isoformat()}")
1287
+ elif key == "categories":
1288
+ categories_value = (
1289
+ value if isinstance(value, str) else ",".join(value)
1290
+ )
1291
+ updated_lines.append(
1292
+ f"CATEGORIES:{_safe_vcard_value(categories_value)}"
1293
+ )
1294
+ elif key == "org":
1295
+ # See ORG note in update-existing branch above.
1296
+ org_value = ";".join(value) if isinstance(value, list) else value
1297
+ updated_lines.append(f"ORG:{_safe_vcard_value(org_value)}")
1298
+ elif key == "title":
1299
+ updated_lines.append(f"TITLE:{_safe_vcard_value(value)}")
1300
+ elif key == "url":
1301
+ # Only the first URL is written on add-new; see note in the
1302
+ # update-existing branch above.
1303
+ url_value = value[0] if isinstance(value, list) and value else value
1304
+ if url_value:
1305
+ updated_lines.append(f"URL:{_safe_vcard_value(url_value)}")
1306
+ elif key == "adr":
1307
+ updated_lines.extend(_adr_line(e) for e in value)
1308
+
1309
+ # Add the END:VCARD line
1310
+ updated_lines.append("END:VCARD")
1311
+
1312
+ # Re-fold on the way out and join with CRLF, so an updated card is framed
1313
+ # exactly like a created one (``Contact.to_vcard()``) instead of the LF
1314
+ # this used to emit. Caveat: ``fold_line`` counts characters, not octets,
1315
+ # so a multibyte line can exceed RFC 6350's 75-octet target — it never
1316
+ # splits a codepoint, Sabre accepts it, and using the library helper keeps
1317
+ # create and update on one folding rule rather than inventing a second.
1318
+ physical_lines: list[str] = []
1319
+ for logical_line in updated_lines:
1320
+ physical_lines.extend(fold_line(logical_line))
1321
+ return "\r\n".join(physical_lines) + "\r\n"