Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
30 changes: 22 additions & 8 deletions pkg/connector/external_carddav.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +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)

// Step 5: Build lookup caches
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. 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
Expand All @@ -147,13 +167,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), keptPhotos
}

// GetContactInfo looks up a contact by phone number or email.
Expand Down
102 changes: 102 additions & 0 deletions pkg/connector/macoun_contact_photo.go
Original file line number Diff line number Diff line change
@@ -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
}
93 changes: 93 additions & 0 deletions pkg/connector/macoun_contact_photo_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
Loading