From 441c0bbf3f8431bb242f10e2038382f2353fe7ab Mon Sep 17 00:00:00 2001 From: Grayson Adams Date: Fri, 27 Nov 2026 00:18:49 -0500 Subject: [PATCH 1/3] test: cover contact photos re-encoded between CardDAV syncs --- pkg/connector/external_carddav.go | 22 +++-- pkg/connector/macoun_contact_photo_test.go | 93 ++++++++++++++++++++++ 2 files changed, 107 insertions(+), 8 deletions(-) create mode 100644 pkg/connector/macoun_contact_photo_test.go diff --git a/pkg/connector/external_carddav.go b/pkg/connector/external_carddav.go index 40eccdb..33f203e 100644 --- a/pkg/connector/external_carddav.go +++ b/pkg/connector/external_carddav.go @@ -128,7 +128,19 @@ func (c *externalCardDAVClient) SyncContacts(log zerolog.Logger) error { // Step 4.5: Download any photo URLs (e.g. Google uses URL-based PHOTO fields) downloadContactPhotos(allContacts, log) - // Step 5: Build lookup caches + phoneKeys, emailKeys := c.storeContacts(allContacts) + + log.Info(). + Int("contacts", len(allContacts)). + Int("phone_keys", phoneKeys). + Int("email_keys", emailKeys). + Msg("Contact cache synced from external CardDAV") + return nil +} + +// storeContacts replaces the lookup caches with a fresh sync's contacts and +// returns the number of phone and email keys indexed. +func (c *externalCardDAVClient) storeContacts(allContacts []*imessage.Contact) (phoneKeys, emailKeys int) { c.mu.Lock() defer c.mu.Unlock() @@ -147,13 +159,7 @@ func (c *externalCardDAVClient) SyncContacts(log zerolog.Logger) error { } } c.lastSync = time.Now() - - log.Info(). - Int("contacts", len(allContacts)). - Int("phone_keys", len(c.byPhone)). - Int("email_keys", len(c.byEmail)). - Msg("Contact cache synced from external CardDAV") - return nil + return len(c.byPhone), len(c.byEmail) } // GetContactInfo looks up a contact by phone number or email. diff --git a/pkg/connector/macoun_contact_photo_test.go b/pkg/connector/macoun_contact_photo_test.go new file mode 100644 index 0000000..b98ea7c --- /dev/null +++ b/pkg/connector/macoun_contact_photo_test.go @@ -0,0 +1,93 @@ +package connector + +import ( + "bytes" + "image" + "image/color" + "image/jpeg" + "testing" + + "github.com/lrhodin/corten-matrix/imessage" +) + +// photoJPEG encodes a 64x64 gradient. nudge adds that much to the red channel +// of one 8x8 block in the corner, which is how Google's two encodings of the +// same contact photo differ after decoding. +func photoJPEG(t *testing.T, base uint8, nudge uint8) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, 64, 64)) + for y := 0; y < 64; y++ { + for x := 0; x < 64; x++ { + img.Set(x, y, color.RGBA{R: base + uint8(x), G: uint8(y * 3), B: 100, A: 255}) + } + } + for y := 56; y < 64; y++ { + for x := 56; x < 64; x++ { + c := img.RGBAAt(x, y) + c.R += nudge + img.SetRGBA(x, y, c) + } + } + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func syncPhoto(c *externalCardDAVClient, photo []byte) { + c.storeContacts([]*imessage.Contact{{ + FirstName: "Sam", + Phones: []string{"+15555550123"}, + Avatar: photo, + }}) +} + +func cachedPhoto(t *testing.T, c *externalCardDAVClient) []byte { + t.Helper() + ct, _ := c.GetContactInfo("+15555550123") + if ct == nil { + t.Fatal("contact not found") + } + return ct.Avatar +} + +func TestContactPhotoReencodeKeepsCachedBytes(t *testing.T) { + first := photoJPEG(t, 10, 0) + reencoded := photoJPEG(t, 10, 2) + if bytes.Equal(first, reencoded) { + t.Fatal("test photos must differ in bytes") + } + c := &externalCardDAVClient{} + syncPhoto(c, first) + syncPhoto(c, reencoded) + if !bytes.Equal(cachedPhoto(t, c), first) { + t.Fatal("a re-encoded copy of the same photo replaced the cached bytes") + } +} + +func TestContactPhotoRealChangeReplacesCachedBytes(t *testing.T) { + first := photoJPEG(t, 10, 0) + changed := photoJPEG(t, 120, 0) + c := &externalCardDAVClient{} + syncPhoto(c, first) + syncPhoto(c, changed) + if !bytes.Equal(cachedPhoto(t, c), changed) { + t.Fatal("a different photo did not replace the cached bytes") + } +} + +func TestContactPhotoFirstSyncAndUndecodable(t *testing.T) { + c := &externalCardDAVClient{} + syncPhoto(c, nil) + first := photoJPEG(t, 10, 0) + syncPhoto(c, first) + if !bytes.Equal(cachedPhoto(t, c), first) { + t.Fatal("a photo added to a contact without one was not stored") + } + junk := []byte("not an image") + syncPhoto(c, junk) + if !bytes.Equal(cachedPhoto(t, c), junk) { + t.Fatal("bytes that cannot be decoded must replace the cache, not be compared") + } +} From 2a6f3be4570c80141b863b9c4f4a697a3bf43fb7 Mon Sep 17 00:00:00 2001 From: Grayson Adams Date: Fri, 27 Nov 2026 00:23:05 -0500 Subject: [PATCH 2/3] fix: keep cached contact photo when carddav re-encodes it Google's CardDAV serves some inline contact photos in two encodings that alternate between requests (about 1 in 40 fetches for one contact). They decode to the same picture, differing by at most 2 levels in one 8x8 block, but the ghost avatar ID is a hash of the bytes, so each switch re-uploaded the photo and re-set the avatar in all 15 of that contact's rooms: 66 avatar changes and about 1,000 member events in three days. On each sync, a fresh photo that decodes to the same size and within a small pixel difference of the cached one now keeps the cached bytes. --- pkg/connector/external_carddav.go | 16 +++- pkg/connector/macoun_contact_photo.go | 102 ++++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 4 deletions(-) create mode 100644 pkg/connector/macoun_contact_photo.go diff --git a/pkg/connector/external_carddav.go b/pkg/connector/external_carddav.go index 33f203e..b3460eb 100644 --- a/pkg/connector/external_carddav.go +++ b/pkg/connector/external_carddav.go @@ -128,22 +128,30 @@ func (c *externalCardDAVClient) SyncContacts(log zerolog.Logger) error { // Step 4.5: Download any photo URLs (e.g. Google uses URL-based PHOTO fields) downloadContactPhotos(allContacts, log) - phoneKeys, emailKeys := c.storeContacts(allContacts) + phoneKeys, emailKeys, keptPhotos := c.storeContacts(allContacts) log.Info(). Int("contacts", len(allContacts)). Int("phone_keys", phoneKeys). Int("email_keys", emailKeys). + Int("reencoded_photos_kept", keptPhotos). Msg("Contact cache synced from external CardDAV") return nil } // storeContacts replaces the lookup caches with a fresh sync's contacts and -// returns the number of phone and email keys indexed. -func (c *externalCardDAVClient) storeContacts(allContacts []*imessage.Contact) (phoneKeys, emailKeys int) { +// returns the number of phone and email keys indexed. A photo that is only a +// re-encode of the cached one keeps the cached bytes (macoun_contact_photo.go); +// keptPhotos counts those. +func (c *externalCardDAVClient) storeContacts(allContacts []*imessage.Contact) (phoneKeys, emailKeys, keptPhotos int) { c.mu.Lock() defer c.mu.Unlock() + oldPhone, oldEmail := c.byPhone, c.byEmail + keptPhotos = keepEquivalentPhotos(allContacts, func(ct *imessage.Contact) *imessage.Contact { + return previousContact(oldPhone, oldEmail, ct) + }) + c.byPhone = make(map[string]*imessage.Contact, len(allContacts)*2) c.byEmail = make(map[string]*imessage.Contact, len(allContacts)) c.contacts = allContacts @@ -159,7 +167,7 @@ func (c *externalCardDAVClient) storeContacts(allContacts []*imessage.Contact) ( } } c.lastSync = time.Now() - return len(c.byPhone), len(c.byEmail) + return len(c.byPhone), len(c.byEmail), keptPhotos } // GetContactInfo looks up a contact by phone number or email. diff --git a/pkg/connector/macoun_contact_photo.go b/pkg/connector/macoun_contact_photo.go new file mode 100644 index 0000000..1076c04 --- /dev/null +++ b/pkg/connector/macoun_contact_photo.go @@ -0,0 +1,102 @@ +package connector + +import ( + "bytes" + "image" + _ "image/jpeg" // decoders for samePhoto + _ "image/png" + "strings" + + "github.com/lrhodin/corten-matrix/imessage" +) + +// Google's CardDAV serves some contact photos in two encodings that alternate +// between requests: the same picture, differing in a few bytes and, decoded, +// by a level or two in one 8x8 block. The ghost avatar ID is a hash of the +// photo bytes, so without this every switch reads as a new photo and re-sets +// the avatar in each of the contact's rooms. keepEquivalentPhotos holds on to +// the cached bytes when the fresh ones are the same picture. + +// Limits for treating two decoded photos as the same picture. A re-encode +// differs by a level or two in a handful of pixels; a new photo differs by far +// more than either limit. +const ( + samePhotoMaxMeanDiff = 1.0 // average per-channel difference, 0-255 scale + samePhotoMaxPixelDiff = 24 // largest single per-channel difference +) + +// keepEquivalentPhotos gives each fresh contact the previous sync's photo +// bytes when its new photo is the same picture. old looks a contact up in the +// previous cache. +func keepEquivalentPhotos(fresh []*imessage.Contact, old func(*imessage.Contact) *imessage.Contact) int { + kept := 0 + for _, ct := range fresh { + if len(ct.Avatar) == 0 { + continue + } + prev := old(ct) + if prev == nil || len(prev.Avatar) == 0 || bytes.Equal(prev.Avatar, ct.Avatar) { + continue + } + if samePhoto(prev.Avatar, ct.Avatar) { + ct.Avatar = prev.Avatar + kept++ + } + } + return kept +} + +// previousContact finds ct in the previous sync's indexes, by phone first and +// then by email, the same order GetContactInfo resolves a handle. +func previousContact(byPhone, byEmail map[string]*imessage.Contact, ct *imessage.Contact) *imessage.Contact { + for _, phone := range ct.Phones { + for _, suffix := range phoneSuffixes(phone) { + if o, ok := byPhone[suffix]; ok { + return o + } + } + } + for _, email := range ct.Emails { + if o, ok := byEmail[strings.ToLower(email)]; ok { + return o + } + } + return nil +} + +// samePhoto reports whether two encoded images show the same picture. Images +// that fail to decode or differ in size are never the same. +func samePhoto(a, b []byte) bool { + imgA, _, errA := image.Decode(bytes.NewReader(a)) + imgB, _, errB := image.Decode(bytes.NewReader(b)) + if errA != nil || errB != nil { + return false + } + ra, rb := imgA.Bounds(), imgB.Bounds() + if ra.Dx() != rb.Dx() || ra.Dy() != rb.Dy() || ra.Empty() { + return false + } + var total uint64 + for y := 0; y < ra.Dy(); y++ { + for x := 0; x < ra.Dx(); x++ { + ar, ag, ab, _ := imgA.At(ra.Min.X+x, ra.Min.Y+y).RGBA() + br, bg, bb, _ := imgB.At(rb.Min.X+x, rb.Min.Y+y).RGBA() + for _, d := range [3]uint32{absDiff(ar, br), absDiff(ag, bg), absDiff(ab, bb)} { + d >>= 8 // 16-bit color to 0-255 + if d > samePhotoMaxPixelDiff { + return false + } + total += uint64(d) + } + } + } + mean := float64(total) / float64(ra.Dx()*ra.Dy()*3) + return mean <= samePhotoMaxMeanDiff +} + +func absDiff(a, b uint32) uint32 { + if a > b { + return a - b + } + return b - a +} From 203d929fa9f500dda9c225d85ad0c4112fa288fb Mon Sep 17 00:00:00 2001 From: Grayson Adams Date: Fri, 27 Nov 2026 01:08:56 -0500 Subject: [PATCH 3/3] docs: note the contact photo fix in the changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d956d..7369a6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ * Fixed group ghosts being removed from a room whose stored roster was unknown. * Fixed starting a chat through the provisioning API with a bare phone number or email (no `tel:` or `mailto:`) failing with IDS error 6001. +* Fixed a contact's avatar being set again in every shared room whenever an + external CardDAV server (seen with Google) served the same photo in a + different encoding. # v0.1.0 (2026-11-26)