forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphone_notification_service.go
More file actions
355 lines (295 loc) · 14.3 KB
/
Copy pathphone_notification_service.go
File metadata and controls
355 lines (295 loc) · 14.3 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package services
import (
"context"
"errors"
"fmt"
"time"
"github.com/NdoleStudio/httpsms/pkg/events"
cloudevents "github.com/cloudevents/sdk-go/v2"
"firebase.google.com/go/messaging"
"github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/google/uuid"
"github.com/palantir/stacktrace"
)
// PhoneNotificationService sends out notifications to mobile phones
type PhoneNotificationService struct {
service
logger telemetry.Logger
tracer telemetry.Tracer
phoneNotificationRepository repositories.PhoneNotificationRepository
phoneRepository repositories.PhoneRepository
messagingClient *messaging.Client
eventDispatcher *EventDispatcher
}
// NewNotificationService creates a new PhoneNotificationService
func NewNotificationService(
logger telemetry.Logger,
tracer telemetry.Tracer,
messagingClient *messaging.Client,
phoneRepository repositories.PhoneRepository,
phoneNotificationRepository repositories.PhoneNotificationRepository,
dispatcher *EventDispatcher,
) (s *PhoneNotificationService) {
return &PhoneNotificationService{
logger: logger.WithService(fmt.Sprintf("%T", s)),
tracer: tracer,
messagingClient: messagingClient,
phoneNotificationRepository: phoneNotificationRepository,
phoneRepository: phoneRepository,
eventDispatcher: dispatcher,
}
}
// DeleteAllForUser deletes all entities.PhoneNotification for an entities.UserID.
func (service *PhoneNotificationService) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
if err := service.phoneNotificationRepository.DeleteAllForUser(ctx, userID); err != nil {
msg := fmt.Sprintf("could not delete all [entities.PhoneNotification] for user with ID [%s]", userID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("deleted all [entities.PhoneNotification] for user with ID [%s]", userID))
return nil
}
// SendHeartbeatFCM sends a heartbeat message so the phone can request a heartbeat
func (service *PhoneNotificationService) SendHeartbeatFCM(ctx context.Context, payload *events.PhoneHeartbeatMissedPayload) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
phone, err := service.phoneRepository.LoadByID(ctx, payload.UserID, payload.PhoneID)
if err != nil {
msg := fmt.Sprintf("cannot load phone with userID [%s] and phoneID [%s]", payload.UserID, payload.PhoneID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if phone.FcmToken == nil {
msg := fmt.Sprintf("phone with id [%s] has no FCM token", phone.ID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
result, err := service.messagingClient.Send(ctx, &messaging.Message{
Data: map[string]string{
"KEY_HEARTBEAT_ID": time.Now().UTC().Format(time.RFC3339),
},
Android: &messaging.AndroidConfig{
Priority: "high",
},
Token: *phone.FcmToken,
})
if err != nil {
msg := fmt.Sprintf("cannot send heartbeat FCM to phone with id [%s] for user [%s]", phone.ID, phone.UserID)
ctxLogger.Warn(stacktrace.Propagate(err, msg))
return nil
}
ctxLogger.Info(fmt.Sprintf("successfully sent heartbeat FCM [%s] to phone with ID [%s] for user [%s] and monitor [%s]", result, payload.PhoneID, payload.UserID, payload.MonitorID))
return nil
}
// PhoneNotificationSendParams are parameters for sending a notification
type PhoneNotificationSendParams struct {
UserID entities.UserID
PhoneID uuid.UUID
PhoneNotificationID uuid.UUID
Source string
ScheduledAt time.Time
MessageID uuid.UUID
}
// Send sends a message when a message is sent
func (service *PhoneNotificationService) Send(ctx context.Context, params *PhoneNotificationSendParams) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
phone, err := service.phoneRepository.LoadByID(ctx, params.UserID, params.PhoneID)
if err != nil {
msg := fmt.Sprintf("cannot load phone with userID [%s] and phoneID [%s]", params.UserID, params.PhoneID)
return service.handleNotificationFailed(ctx, errors.New(msg), params)
}
if phone.FcmToken == nil {
msg := fmt.Sprintf("phone with id [%s] has no FCM token", phone.ID)
return service.handleNotificationFailed(ctx, errors.New(msg), params)
}
ttl := phone.MessageExpirationDuration()
result, err := service.messagingClient.Send(ctx, &messaging.Message{
Data: map[string]string{
"KEY_MESSAGE_ID": params.MessageID.String(),
},
Android: &messaging.AndroidConfig{
Priority: "normal",
TTL: &ttl,
},
Token: *phone.FcmToken,
})
if err != nil {
ctxLogger.Warn(stacktrace.Propagate(err, fmt.Sprintf("cannot send FCM to phone with ID [%s] for user with ID [%s] and message [%s]", phone.ID, phone.UserID, params.MessageID)))
msg := fmt.Sprintf("cannot send notification for to your phone [%s]. Reinstall the httpSMS app on your Android phone.", phone.PhoneNumber)
return service.handleNotificationFailed(ctx, errors.New(msg), params)
}
return service.handleNotificationSent(ctx, phone, result, params)
}
// PhoneNotificationScheduleParams are parameters for sending a notification
type PhoneNotificationScheduleParams struct {
UserID entities.UserID
Owner string
Source string
Encrypted bool
Contact string
Content string
SIM entities.SIM
MessageID uuid.UUID
}
// Schedule a notification to be sent to a phone
func (service *PhoneNotificationService) Schedule(ctx context.Context, params *PhoneNotificationScheduleParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
phone, err := service.phoneRepository.Load(ctx, params.UserID, params.Owner)
if err != nil {
msg := fmt.Sprintf("cannot load phone with userID [%s] and phone [%s]", params.UserID, params.Owner)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
notification := &entities.PhoneNotification{
ID: uuid.New(),
MessageID: params.MessageID,
UserID: params.UserID,
PhoneID: phone.ID,
Status: entities.PhoneNotificationStatusPending,
ScheduledAt: time.Now().UTC(),
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
}
if err = service.phoneNotificationRepository.Schedule(ctx, phone.MessagesPerMinute, notification); err != nil {
msg := fmt.Sprintf("cannot schedule notification for message [%s] to phone [%s]", params.MessageID, phone.ID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if err = service.dispatchMessageNotificationScheduled(ctx, params, notification); err != nil {
ctxLogger.Error(err)
}
if err = service.dispatchMessageNotificationSend(ctx, params.Source, notification); err != nil {
return service.tracer.WrapErrorSpan(span, err)
}
ctxLogger.Info(fmt.Sprintf("message with id [%s] notification scheduled for [%s] with id [%s]", params.MessageID, notification.ScheduledAt, notification.ID))
return nil
}
func (service *PhoneNotificationService) dispatchMessageNotificationSend(ctx context.Context, source string, notification *entities.PhoneNotification) error {
event, err := service.createMessageNotificationSendEvent(source, &events.MessageNotificationSendPayload{
MessageID: notification.MessageID,
UserID: notification.UserID,
PhoneID: notification.PhoneID,
ScheduledAt: notification.ScheduledAt,
NotificationID: notification.ID,
})
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create [%s] event for notification [%s]", events.EventTypeMessageNotificationSend, notification.ID))
}
if _, err = service.eventDispatcher.DispatchWithTimeout(ctx, event, notification.ScheduledAt.Sub(time.Now())); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), notification.ID))
}
return nil
}
func (service *PhoneNotificationService) dispatchMessageNotificationScheduled(ctx context.Context, params *PhoneNotificationScheduleParams, notification *entities.PhoneNotification) error {
event, err := service.createMessageNotificationScheduledEvent(params.Source, &events.MessageNotificationScheduledPayload{
MessageID: notification.MessageID,
Owner: params.Owner,
Contact: params.Contact,
Encrypted: params.Encrypted,
Content: params.Content,
SIM: params.SIM,
UserID: notification.UserID,
PhoneID: notification.PhoneID,
ScheduledAt: notification.ScheduledAt,
NotificationID: notification.ID,
})
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create [%s] event for notification [%s]", events.EventTypeMessageNotificationScheduled, notification.ID))
}
if err = service.eventDispatcher.Dispatch(ctx, event); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), notification.ID))
}
return nil
}
func (service *PhoneNotificationService) handleNotificationFailed(ctx context.Context, err error, params *PhoneNotificationSendParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
msg := fmt.Sprintf("cannot send notification for message [%s] to phone [%s]", params.MessageID, params.PhoneNotificationID)
ctxLogger.Warn(stacktrace.Propagate(err, msg))
event, err := service.createMessageNotificationFailedEvent(params.Source, err.Error(), params)
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create [%s] event for notification [%s]", events.EventTypeMessageNotificationFailed, params.PhoneNotificationID))
}
if err = service.eventDispatcher.Dispatch(ctx, event); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), params.PhoneNotificationID))
}
service.updateStatus(ctx, params.PhoneNotificationID, entities.PhoneNotificationStatusFailed)
return nil
}
func (service *PhoneNotificationService) handleNotificationSent(ctx context.Context, phone *entities.Phone, result string, params *PhoneNotificationSendParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
ctxLogger.Info(fmt.Sprintf("sent notification [%s] for message [%s] to phone [%s]", result, params.MessageID, params.PhoneID))
event, err := service.createMessageNotificationSentEvent(params.Source, phone, result, params)
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create [%s] event for notification [%s]", events.EventTypeMessageNotificationSent, params.PhoneNotificationID))
}
if err = service.eventDispatcher.Dispatch(ctx, event); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), params.PhoneNotificationID))
}
service.updateStatus(ctx, params.PhoneNotificationID, entities.PhoneNotificationStatusSent)
return nil
}
func (service *PhoneNotificationService) createMessageNotificationScheduledEvent(source string, payload *events.MessageNotificationScheduledPayload) (cloudevents.Event, error) {
return service.createEvent(events.EventTypeMessageNotificationScheduled, source, payload)
}
func (service *PhoneNotificationService) createMessageNotificationSendEvent(source string, payload *events.MessageNotificationSendPayload) (cloudevents.Event, error) {
return service.createEvent(events.EventTypeMessageNotificationSend, source, payload)
}
func (service *PhoneNotificationService) createMessageNotificationSentEvent(source string, phone *entities.Phone, fcmMessageID string, params *PhoneNotificationSendParams) (cloudevents.Event, error) {
event := cloudevents.NewEvent()
event.SetSource(source)
event.SetType(events.EventTypeMessageNotificationSent)
event.SetTime(time.Now().UTC())
event.SetID(uuid.New().String())
payload := events.MessageNotificationSentPayload{
MessageID: params.MessageID,
UserID: params.UserID,
PhoneID: params.PhoneID,
ScheduledAt: params.ScheduledAt,
MessageExpirationDuration: phone.MessageExpirationDuration(),
FcmMessageID: fcmMessageID,
NotificationSentAt: time.Now().UTC(),
NotificationID: params.PhoneNotificationID,
}
if err := event.SetData(cloudevents.ApplicationJSON, payload); err != nil {
msg := fmt.Sprintf("cannot encode %T [%#+v] as JSON", payload, payload)
return event, stacktrace.Propagate(err, msg)
}
return event, nil
}
func (service *PhoneNotificationService) createMessageNotificationFailedEvent(source string, errorMessage string, params *PhoneNotificationSendParams) (cloudevents.Event, error) {
event := cloudevents.NewEvent()
event.SetSource(source)
event.SetType(events.EventTypeMessageNotificationFailed)
event.SetTime(time.Now().UTC())
event.SetID(uuid.New().String())
payload := events.MessageNotificationFailedPayload{
MessageID: params.MessageID,
UserID: params.UserID,
PhoneID: params.PhoneID,
ErrorMessage: errorMessage,
NotificationFailedAt: time.Now().UTC(),
NotificationID: params.PhoneNotificationID,
}
if err := event.SetData(cloudevents.ApplicationJSON, payload); err != nil {
msg := fmt.Sprintf("cannot encode %T [%#+v] as JSON", payload, payload)
return event, stacktrace.Propagate(err, msg)
}
return event, nil
}
func (service *PhoneNotificationService) updateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
err := service.phoneNotificationRepository.UpdateStatus(ctx, notificationID, status)
if err != nil {
msg := fmt.Sprintf("cannot update status of notificaiton with id [%s] to [%s]", notificationID, status)
ctxLogger.Error(stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("updated status of notificaiton with id [%s] to [%s]", notificationID, status))
}