aboutsummaryrefslogtreecommitdiff
path: root/contact.go
blob: 7d6446ce894128ac007bdff2ec40753195144834 (plain)
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
package acme

import (
	"encoding"
	"encoding/json"
	"errors"
	"net/mail"
	"strings"
)

var errInvalidContact = errors.New("Ivalid contact")

type Contact interface {
	encoding.TextMarshaler
}

type Mail string

func (m Mail) MarshalText() ([]byte, error) {
	return []byte("mailto:" + m), nil
}

type Phone string

func (ph Phone) MarshalText() ([]byte, error) {
	return []byte("tel:" + ph), nil
}

type Contacts []Contact

func (c *Contacts) UnmarshalJSON(b []byte) error {
	var tmp []string
	err := json.Unmarshal(b, &tmp)
	if err != nil {
		return err
	}
	*c = nil // invalidate old value
	for _, s := range tmp {
		switch {
		case strings.HasPrefix(s, "mailto:"):
			*c = append(*c, Mail(s[7:]))
		case strings.HasPrefix(s, "tel:"):
			*c = append(*c, Phone(s[4:]))
		default:
			return errInvalidContact
		}
	}
	return nil
}

func (c *Contacts) AddMail(email string) error {
	m, err := mail.ParseAddress(email)
	if err != nil {
		return err
	}
	*c = append(*c, Mail(m.Address))
	return nil
}

func (c *Contacts) AddPhone(phone string) error {
	if ph := strings.TrimSpace(phone); ph != "" {
		*c = append(*c, Phone(ph))
	}
	return nil
}