-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
304 lines (251 loc) · 7.31 KB
/
message.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package ratatxt
import (
"fmt"
"strings"
"time"
)
// Message errors types.
const (
MessageErrNotFound Errors = iota + 4000
MessageErrRequiredID
)
// Message error definition
func init() {
errorsText[MessageErrNotFound] = "message not found"
errorsText[MessageErrRequiredID] = "message id is required"
}
// MessageKind represents message kind.
type MessageKind uint
const (
MessageKindInbox MessageKind = 10
MessageKindOutbox MessageKind = 20
)
// MessageStatus represents message status.
type MessageStatus uint
// Inbox message statuses.
const (
MessageStatusInboxNew MessageStatus = 110
MessageStatusInboxRead MessageStatus = 120
MessageStatusInboxFailed MessageStatus = 140
MessageStatusInboxError MessageStatus = 150
)
// Outbox message statuses.
const (
MessageStatusOutboxQueued MessageStatus = 200
MessageStatusOutboxSending MessageStatus = 210
MessageStatusOutboxSent MessageStatus = 220
MessageStatusOutboxFailed MessageStatus = 240
MessageStatusOutboxError MessageStatus = 250
)
// Message represents user's message information.
type Message struct {
ID ID `json:"id" gorm:"primaryKey;type:CHAR(20)"`
UserID ID `json:"user_id"`
DeviceID ID `json:"device_id"`
Kind MessageKind `json:"kind"`
Status MessageStatus `json:"status"`
Address string `json:"address"`
Text string `json:"text"`
Timestamp int64 `json:"timestamp"`
RetryCount int `json:"retry_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Device *Device `json:"device,omitempty" gorm:"-"`
}
func (m Message) setDefaults() *Message {
switch m.Kind {
case MessageKindInbox:
m.Status = MessageStatusInboxNew
case MessageKindOutbox:
m.Status = MessageStatusOutboxQueued
}
if m.Timestamp == 0 {
m.Timestamp = time.Now().Unix() * 1000
}
return &m
}
// MessageFilter represents message filter.
type MessageFilter struct {
ID ID `db:"id,omitempty"`
UserID ID `db:"user_id,omitempty"`
DeviceID ID `db:"device_id,omitempty"`
Kind MessageKind `db:"kind,omitempty"`
Status MessageStatus `db:"status,omitempty"`
Address string `db:"address,omitempty"`
}
// Messages returns a list of messages by filter.
func (c *Core) Messages(f *MessageFilter) ([]*Message, error) {
var list []*Message
if err := c.store.List(&list, f); err != nil {
return nil, err
}
return list, nil
}
// Message returns message details by filter and returns error if no result.
func (c *Core) Message(f MessageFilter) (*Message, error) {
list, err := c.Messages(&f)
if err != nil {
return nil, err
}
if len(list) == 0 {
return nil, DeviceErrNotFound
}
msg := list[0]
msg.Device, _ = c.Device(DeviceFilter{ID: msg.DeviceID})
return msg, nil
}
// MessageByID returns message details by id.
func (c *Core) MessageByID(id ID) (*Message, error) {
return c.Message(MessageFilter{ID: id})
}
// MessageCreateParam represents parameters to create a message.
type MessageCreateParam struct {
UserID ID `json:"user_id"`
DeviceID ID `json:"device_id"`
Kind MessageKind `json:"kind"`
Status MessageStatus `json:"status"`
Address string `json:"address"`
Text string `json:"text"`
Timestamp int64 `json:"timestamp"`
}
func (p *MessageCreateParam) validate() error {
if p.UserID.IsEmpty() {
return fmt.Errorf("user_id is required")
}
p.Address = strings.TrimSpace(p.Address)
p.Text = strings.TrimSpace(p.Text)
if p.DeviceID.IsEmpty() || p.Address == "" || p.Text == "" ||
p.Kind == 0 {
return fmt.Errorf("device_id, address, and text are required")
}
return nil
}
// CreateMessage creates new message to datastore.
func (c *Core) CreateMessage(p MessageCreateParam) (*Message, error) {
if err := p.validate(); err != nil {
return nil, err
}
// Check a valid device id.
if _, err := c.DeviceByID(p.DeviceID); err != nil {
return nil, err
}
// Set default values and create new device record.
msg := &Message{
UserID: p.UserID,
DeviceID: p.DeviceID,
Kind: p.Kind,
Status: p.Status,
Address: p.Address,
Text: p.Text,
Timestamp: p.Timestamp,
}
msg = msg.setDefaults()
if err := c.store.Create(msg); err != nil {
return nil, err
}
return msg, nil
}
// PushInbox creates new inbox kind message and notifies device owners registered webhooks.
func (c *Core) PushInbox(p MessageCreateParam) (*Message, error) {
p.Kind = MessageKindInbox
msg, err := c.CreateMessage(p)
if err != nil {
return nil, err
}
go c.sendWebhookPayload(*msg)
return msg, nil
}
// SendOutbox creates new outbox kind message and send command to device to send SMS.
func (c *Core) SendOutbox(p MessageCreateParam) (*Message, error) {
p.Kind = MessageKindOutbox
msg, err := c.CreateMessage(p)
if err != nil {
return nil, err
}
// Send command to device to send the SMS.
dev, err := c.DeviceByID(msg.DeviceID)
if err != nil {
return nil, err
}
topicID, err := dev.topicID()
if err != nil {
return nil, err
}
if err = c.deviceCmd.Forward(topicID, msg.ID.String(), msg.Address, msg.Text); err != nil {
return nil, err
}
return msg, nil
}
// OutboxUpdateParam represents parameters to update an outbox message.
type OutboxUpdateParam struct {
ID ID `json:"id"`
UserID ID `json:"user_id"`
Status MessageStatus `json:"status"`
}
func (p *OutboxUpdateParam) validate() error {
if p.UserID.IsEmpty() {
return fmt.Errorf("user_id is required")
}
if p.ID.IsEmpty() || p.Status == 0 {
return fmt.Errorf("id, user_id, status are required")
}
return nil
}
// UpdateOutbox updates existing message outbox to datastore.
func (c *Core) UpdateOutbox(p OutboxUpdateParam) (*Message, error) {
if err := p.validate(); err != nil {
return nil, err
}
// Check message ownership.
cur, err := c.Message(MessageFilter{ID: p.ID, UserID: p.UserID, Kind: MessageKindOutbox})
if err != nil {
return nil, err
}
if cur == nil {
return nil, MessageErrNotFound
}
// Update message record.
return c.updateMessageStatusByID(p.ID, p.Status)
}
func (c *Core) updateMessageStatusByID(id ID, s MessageStatus) (*Message, error) {
msg := &Message{ID: id, Status: s}
if err := c.store.Update(msg); err != nil {
return nil, err
}
go c.sendWebhookPayload(*msg)
return msg, nil
}
func (c *Core) sendWebhookPayload(m Message) {
m.Device, _ = c.Device(DeviceFilter{ID: m.DeviceID})
if errs := c.shootWebhooks(m); errs != nil {
for _, err := range errs {
c.logger.Error("send webhook payload errors:", err)
}
}
}
func (c *Core) retrySendOutbox(id ID) error {
msg, err := c.MessageByID(id)
if err != nil {
return err
}
msg.Status = MessageStatusOutboxQueued
msg.RetryCount++
// Requeue on device command to forward.
return c.store.Update(msg)
}
var messageSearchKeywordFields = []string{"id", "address", "text"}
// SearchMessages returns a list of messages and metadata base on search options.
func (c *Core) SearchMessages(opts *SearchOpts) ([]*Message, *SearchMetadata, error) {
if opts != nil {
opts.KeywordFields = messageSearchKeywordFields
}
var list []*Message
meta, err := c.store.Search(&list, opts)
if err != nil {
return nil, nil, err
}
for i, msg := range list {
list[i].Device, _ = c.Device(DeviceFilter{ID: msg.DeviceID})
}
return list, meta, nil
}