-
Notifications
You must be signed in to change notification settings - Fork 2
/
carddav.go
67 lines (61 loc) · 2.19 KB
/
carddav.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"encoding/base64"
"fmt"
"log"
"strings"
"github.com/emersion/go-vcard"
"github.com/go-ldap/ldap/v3"
"github.com/spf13/viper"
)
type CardDAVWorker struct {
channel chan []*ldap.Entry
backend *CardDAVBackend
}
func NewCardDAVWorker(ch chan []*ldap.Entry, backend *CardDAVBackend) *CardDAVWorker {
return &CardDAVWorker{
channel: ch,
backend: backend,
}
}
func (cw *CardDAVWorker) Start() {
logger := log.New(log.Writer(), "[CardDAVWorker] ", log.Ldate|log.Ltime)
for updates := range cw.channel {
if viper.GetBool("carddav.clear_old_entries") {
// clearing all vcfs before updating
logger.Println("Deleting all vCards before sync...")
err := cw.backend.ClearAddressBook()
if err != nil {
log.Fatal(err)
}
}
logger.Printf("Creating %d new vCard files...\n", len(updates))
for _, update := range updates {
vCard := createVCardFromLdap(update)
cw.backend.SaveContact(update.GetAttributeValue(viper.GetString("ldap.unique_id_field")), vCard)
}
}
}
func createVCardFromLdap(entry *ldap.Entry) *vcard.Card {
card := make(vcard.Card)
card.SetValue(vcard.FieldName, strings.Join([]string{entry.GetAttributeValue("sn"), entry.GetAttributeValue("givenName")}, ";"))
card.Set(vcard.FieldEmail, &vcard.Field{
Value: entry.GetAttributeValue("mail"),
Params: vcard.Params{
vcard.ParamType: {vcard.TypeWork},
},
})
card.Set(vcard.FieldTelephone, &vcard.Field{
Value: entry.GetAttributeValue(viper.GetString("ldap.phone_field")),
Params: vcard.Params{
vcard.ParamType: {vcard.TypeCell},
},
})
card.SetValue(vcard.FieldUID, entry.GetAttributeValue(viper.GetString("ldap.unique_id_field")))
card.SetValue(vcard.FieldPhoto, fmt.Sprintf("data:image/jpeg;base64,%s", base64.StdEncoding.EncodeToString([]byte(entry.GetAttributeValue(viper.GetString("ldap.avatar_field"))))))
if entry.GetAttributeValue("birthyear") != "" || entry.GetAttributeValue("birthmonth") != "" || entry.GetAttributeValue("birthday") != "" {
card.SetValue(vcard.FieldBirthday, fmt.Sprintf("%s%02s%02s", entry.GetAttributeValue("birthyear"), entry.GetAttributeValue("birthmonth"), entry.GetAttributeValue("birthday")))
}
card.SetValue(vcard.FieldVersion, "3.0")
return &card
}