1package config
2
3import (
4 "fmt"
5 "runtime"
6
7 "github.com/floatpane/matcha/clib/macos"
8 "github.com/floatpane/matcha/internal/collections"
9)
10
11// SyncMacOSContacts fetches contacts from the macOS Contacts framework
12// and merges them into the local contacts cache for all configured accounts.
13func SyncMacOSContacts() error {
14 if runtime.GOOS != "darwin" {
15 return nil
16 }
17 cfg, err := LoadConfig()
18 if err != nil {
19 return err
20 }
21 return SyncMacOSContactsForAccounts(cfg.GetAccountIDs())
22}
23
24// SyncMacOSContactsForAccounts fetches contacts from the macOS Contacts framework
25// and merges them into the local contacts cache for the given accounts.
26func SyncMacOSContactsForAccounts(accountIDs []string) error {
27 if runtime.GOOS != "darwin" {
28 return nil
29 }
30
31 macContacts, err := macos.FetchContacts()
32 if err != nil {
33 return fmt.Errorf("failed to fetch macOS contacts: %w", err)
34 }
35
36 accountIDs = collections.UniqueNonEmpty(accountIDs)
37 for _, mc := range macContacts {
38 for _, email := range mc.Emails {
39 for _, accountID := range accountIDs {
40 if err := AddContactForAccount(mc.Name, email, accountID); err != nil {
41 // We continue even if one fails
42 continue
43 }
44 }
45 }
46 }
47
48 return nil
49}