aboutsummaryrefslogtreecommitdiff
path: root/contact.go
blob: 2a69ebecaee8757a238fefe41df1fd461c4c6b79 (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
66
67
68
69
70
71
72
73
74
package acme

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

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

type Contact interface {
	encoding.TextMarshaler
}

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
}

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
}

func NewMail(email string) (Mail, error) {
	m, err := mail.ParseAddress(email)
	if err != nil {
		return "", err
	}
	return Mail(m.Address), nil
}

func NewPhone(phone string) (Phone, error) {
	return Phone(phone), nil
}

func NewContacts(email, phone string) (Contacts, error) {
	m, err := NewMail(email)
	if err != nil {
		return nil, err
	}
	c := Contacts{m}
	if phone != "" {
		p, _ := NewPhone(phone)
		c = append(c, p)
	}
	return c, nil
}