forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
msg.go
109 lines (88 loc) · 2.51 KB
/
msg.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package courier
import (
"bytes"
"errors"
"strconv"
"strings"
"time"
null "gopkg.in/guregu/null.v3"
"github.com/nyaruka/gocommon/urns"
uuid "github.com/satori/go.uuid"
)
// ErrMsgNotFound is returned when trying to queue the status for a Msg that doesn't exit
var ErrMsgNotFound = errors.New("message not found")
// MsgID is our typing of the db int type
type MsgID struct {
null.Int
}
// NewMsgID creates a new MsgID for the passed in int64
func NewMsgID(id int64) MsgID {
return MsgID{null.NewInt(id, true)}
}
// String satisfies the Stringer interface
func (i MsgID) String() string {
if i.Valid {
return strconv.FormatInt(i.Int64, 10)
}
return "null"
}
// NilMsgID is our nil value for MsgID
var NilMsgID = MsgID{null.NewInt(0, false)}
// MsgUUID is the UUID of a message which has been received
type MsgUUID struct {
uuid.UUID
}
// NilMsgUUID is a "zero value" message UUID
var NilMsgUUID = MsgUUID{uuid.Nil}
// NewMsgUUID creates a new unique message UUID
func NewMsgUUID() MsgUUID {
return MsgUUID{uuid.NewV4()}
}
// NewMsgUUIDFromString creates a new message UUID for the passed in string
func NewMsgUUIDFromString(uuidString string) MsgUUID {
uuid, _ := uuid.FromString(uuidString)
return MsgUUID{uuid}
}
//-----------------------------------------------------------------------------
// Msg interface
//-----------------------------------------------------------------------------
// Msg is our interface to represent an incoming or outgoing message
type Msg interface {
ID() MsgID
UUID() MsgUUID
Text() string
Attachments() []string
ExternalID() string
URN() urns.URN
ContactName() string
QuickReplies() []string
Channel() Channel
ReceivedOn() *time.Time
SentOn() *time.Time
HighPriority() bool
WithContactName(name string) Msg
WithReceivedOn(date time.Time) Msg
WithExternalID(id string) Msg
WithID(id MsgID) Msg
WithUUID(uuid MsgUUID) Msg
WithAttachment(url string) Msg
EventID() int64
}
// GetTextAndAttachments returns both the text of our message as well as any attachments, newline delimited
func GetTextAndAttachments(m Msg) string {
buf := bytes.NewBuffer([]byte(m.Text()))
for _, a := range m.Attachments() {
_, url := SplitAttachment(a)
buf.WriteString("\n")
buf.WriteString(url)
}
return buf.String()
}
// SplitAttachment takes an attachment string and returns the media type and URL for the attachment
func SplitAttachment(attachment string) (string, string) {
parts := strings.SplitN(attachment, ":", 2)
if len(parts) < 2 {
return "", parts[0]
}
return parts[0], parts[1]
}