Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
rename phone notification service
Acho Arnold2a125d7e4355
diff --git a/api/pkg/di/container.go b/api/pkg/di/container.goindex 020c05d4..90614398 100644--- a/api/pkg/di/container.go+++ b/api/pkg/di/container.go@@ -544,9 +544,9 @@ func (container *Container) RegisterMessageThreadListeners() {}}-// RegisterNotificationListeners registers event listeners for listeners.NotificationListener+// RegisterNotificationListeners registers event listeners for listeners.PhoneNotificationListenerfunc (container *Container) RegisterNotificationListeners() {- container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.NotificationListener{}))+ container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.PhoneNotificationListener{}))_, routes := listeners.NewNotificationListener(container.Logger(),container.Tracer(),@@ -583,8 +583,8 @@ func (container *Container) MessageService() (service *services.MessageService))}-// NotificationService creates a new instance of services.NotificationService-func (container *Container) NotificationService() (service *services.NotificationService) {+// NotificationService creates a new instance of services.PhoneNotificationService+func (container *Container) NotificationService() (service *services.PhoneNotificationService) {container.logger.Debug(fmt.Sprintf("creating %T", service))return services.NewNotificationService(container.Logger(),diff --git a/api/pkg/entities/heartbeat.go b/api/pkg/entities/heartbeat.goindex 7446eaf5..9874262e 100644--- a/api/pkg/entities/heartbeat.go+++ b/api/pkg/entities/heartbeat.go@@ -12,5 +12,4 @@ type Heartbeat struct {Owner string `json:"owner" gorm:"index:idx_heartbeats_owner_timestamp" example:"+18005550199"`UserID UserID `json:"userID" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`Timestamp time.Time `json:"timestamp" gorm:"index:idx_heartbeats_owner_timestamp" example:"2022-06-05T14:26:01.520828+03:00"`- MessageID uuid.UUID `json:"message_id" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`}diff --git a/api/pkg/events/message_phone_heartbeat_event.go b/api/pkg/events/message_phone_heartbeat_event.godeleted file mode 100644index 16befac6..00000000--- a/api/pkg/events/message_phone_heartbeat_event.go+++ /dev/null@@ -1,15 +0,0 @@-package events--import (- "time"-)--// EventTypeHeartbeatPhoneOutstanding is emitted when the phone requests for outstanding messages-const EventTypeHeartbeatPhoneOutstanding = "heartbeat.phone.outstanding"--// HeartbeatPhoneOutstandingPayload is the payload of the EventTypeHeartbeatPhoneOutstanding event-type HeartbeatPhoneOutstandingPayload struct {- Owner string `json:"owner"`- Timestamp time.Time `json:"timestamp"`- Quantity int `json:"quantity"`-}diff --git a/api/pkg/handlers/handler.go b/api/pkg/handlers/handler.goindex 4bc091d1..80c5a1eb 100644--- a/api/pkg/handlers/handler.go+++ b/api/pkg/handlers/handler.go@@ -72,6 +72,14 @@ func (h *handler) responseOK(c *fiber.Ctx, message string, data interface{}) err})}+func (h *handler) responseCreated(c *fiber.Ctx, message string, data interface{}) error {+ return c.Status(fiber.StatusCreated).JSON(fiber.Map{+ "status": "success",+ "message": message,+ "data": data,+ })+}+func (h *handler) pluralize(value string, count int) string {if count == 1 {return valuediff --git a/api/pkg/handlers/heartbeat_handler.go b/api/pkg/handlers/heartbeat_handler.goindex 4e727325..ee345038 100644--- a/api/pkg/handlers/heartbeat_handler.go+++ b/api/pkg/handlers/heartbeat_handler.go@@ -86,3 +86,46 @@ func (h *HeartbeatHandler) Index(c *fiber.Ctx) error {return h.responseOK(c, fmt.Sprintf("fetched %d %s", len(*heartbeats), h.pluralize("heartbeat", len(*heartbeats))), heartbeats)}++// Store the heartbeat of a phone number+// @Summary Register heartbeat of an owner phone number+// @Description Store the heartbeat to make notify that a phone number is still active+// @Security ApiKeyAuth+// @Tags Heartbeats+// @Accept json+// @Produce json+// @Param payload body requests.HeartbeatStore true "Payload of the heartbeat request"+// @Success 200 {object} responses.HeartbeatResponse+// @Failure 400 {object} responses.BadRequest+// @Failure 401 {object} responses.Unauthorized+// @Failure 422 {object} responses.UnprocessableEntity+// @Failure 500 {object} responses.InternalServerError+// @Router /heartbeats [post]+func (h *HeartbeatHandler) Store(c *fiber.Ctx) error {+ ctx, span := h.tracer.StartFromFiberCtx(c)+ defer span.End()++ ctxLogger := h.tracer.CtxLogger(h.logger, span)++ var request requests.HeartbeatStore+ if err := c.QueryParser(&request); err != nil {+ msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.OriginalURL(), request)+ ctxLogger.Warn(stacktrace.Propagate(err, msg))+ return h.responseBadRequest(c, err)+ }++ if errors := h.validator.ValidateStore(ctx, request.Sanitize()); len(errors) != 0 {+ msg := fmt.Sprintf("validation errors [%s], while storing heartbeat [%+#v]", spew.Sdump(errors), request)+ ctxLogger.Warn(stacktrace.NewError(msg))+ return h.responseUnprocessableEntity(c, errors, "validation errors while storing heartbeat")+ }++ heartbeat, err := h.service.Store(ctx, request.ToStoreParams(h.userFromContext(c)))+ if err != nil {+ msg := fmt.Sprintf("cannot store heartbeat with params [%+#v]", request)+ ctxLogger.Error(stacktrace.Propagate(err, msg))+ return h.responseInternalServerError(c)+ }++ return h.responseCreated(c, "heartbeat created successfully", heartbeat)+}diff --git a/api/pkg/listeners/heartbeat_listener.go b/api/pkg/listeners/heartbeat_listener.goindex 32635890..64113da2 100644--- a/api/pkg/listeners/heartbeat_listener.go+++ b/api/pkg/listeners/heartbeat_listener.go@@ -1,14 +1,11 @@package listenersimport (- "context""fmt""github.com/NdoleStudio/httpsms/pkg/events""github.com/NdoleStudio/httpsms/pkg/services""github.com/NdoleStudio/httpsms/pkg/telemetry"- cloudevents "github.com/cloudevents/sdk-go/v2"- "github.com/palantir/stacktrace")// HeartbeatListener handles cloud events which need to register entities.Heartbeat@@ -30,33 +27,5 @@ func NewHeartbeatListener(service: service,}- return l, map[string]events.EventListener{- events.EventTypeMessagePhoneSending: l.onMessagePhoneSending,- }-}--// onMessagePhoneSending handles the events.EventTypeMessagePhoneSending event-func (listener *HeartbeatListener) onMessagePhoneSending(ctx context.Context, event cloudevents.Event) error {- ctx, span := listener.tracer.Start(ctx)- defer span.End()-- var payload events.MessagePhoneSendingPayload- if err := event.DataAs(&payload); err != nil {- msg := fmt.Sprintf("cannot decode [%s] into [%T]", event.Data(), payload)- return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }-- storeParams := services.HeartbeatStoreParams{- Owner: payload.Owner,- Timestamp: payload.Timestamp,- UserID: payload.UserID,- MessageID: payload.ID,- }-- if _, err := listener.service.Store(ctx, storeParams); err != nil {- msg := fmt.Sprintf("cannot store heartbeat with params [%+#v] for event with ID [%s]", storeParams, event.ID())- return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }-- return nil+ return l, map[string]events.EventListener{}}diff --git a/api/pkg/listeners/notification_listener.go b/api/pkg/listeners/phone_notification_listener.gosimilarity index 76%rename from api/pkg/listeners/notification_listener.gorename to api/pkg/listeners/phone_notification_listener.goindex 4c24c884..700d7597 100644--- a/api/pkg/listeners/notification_listener.go+++ b/api/pkg/listeners/phone_notification_listener.go@@ -13,20 +13,20 @@ import ("github.com/palantir/stacktrace")-// NotificationListener handles cloud events which sends notifications-type NotificationListener struct {+// PhoneNotificationListener handles cloud events which sends notifications+type PhoneNotificationListener struct {logger telemetry.Loggertracer telemetry.Tracer- service *services.NotificationService+ service *services.PhoneNotificationService}-// NewNotificationListener creates a new instance of NotificationListener+// NewNotificationListener creates a new instance of PhoneNotificationListenerfunc NewNotificationListener(logger telemetry.Logger,tracer telemetry.Tracer,- service *services.NotificationService,-) (l *NotificationListener, routes map[string]events.EventListener) {- l = &NotificationListener{+ service *services.PhoneNotificationService,+) (l *PhoneNotificationListener, routes map[string]events.EventListener) {+ l = &PhoneNotificationListener{logger: logger.WithService(fmt.Sprintf("%T", l)),tracer: tracer,service: service,@@ -39,7 +39,7 @@ func NewNotificationListener(}// onMessageAPISent handles the events.EventTypeMessageAPISent event-func (listener *NotificationListener) onMessageAPISent(ctx context.Context, event cloudevents.Event) error {+func (listener *PhoneNotificationListener) onMessageAPISent(ctx context.Context, event cloudevents.Event) error {ctx, span := listener.tracer.Start(ctx)defer span.End()@@ -49,7 +49,7 @@ func (listener *NotificationListener) onMessageAPISent(ctx context.Context, evenreturn listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))}- sendParams := &services.NotificationScheduleParams{+ sendParams := &services.PhoneNotificationScheduleParams{UserID: payload.UserID,Owner: payload.Owner,Source: event.Source(),@@ -65,7 +65,7 @@ func (listener *NotificationListener) onMessageAPISent(ctx context.Context, even}// onMessageNotificationScheduled handles the events.EventTypeMessageNotificationScheduled event-func (listener *NotificationListener) onMessageNotificationScheduled(ctx context.Context, event cloudevents.Event) error {+func (listener *PhoneNotificationListener) onMessageNotificationScheduled(ctx context.Context, event cloudevents.Event) error {ctx, span := listener.tracer.Start(ctx)defer span.End()@@ -75,7 +75,7 @@ func (listener *NotificationListener) onMessageNotificationScheduled(ctx contextreturn listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))}- scheduleParams := &services.NotificationSendParams{+ scheduleParams := &services.PhoneNotificationSendParams{UserID: payload.UserID,PhoneID: payload.PhoneID,Source: event.Source(),diff --git a/api/pkg/requests/heartbeat_store_request.go b/api/pkg/requests/heartbeat_store_request.gonew file mode 100644index 00000000..d3419a38--- /dev/null+++ b/api/pkg/requests/heartbeat_store_request.go@@ -0,0 +1,29 @@+package requests++import (+ "time"++ "github.com/NdoleStudio/httpsms/pkg/entities"+ "github.com/NdoleStudio/httpsms/pkg/services"+)++// HeartbeatStore is the payload for fetching entities.Heartbeat of a phone number+type HeartbeatStore struct {+ request+ Owner string `json:"owner"`+}++// Sanitize sets defaults to MessageOutstanding+func (input *HeartbeatStore) Sanitize() HeartbeatStore {+ input.Owner = input.sanitizeAddress(input.Owner)+ return *input+}++// ToStoreParams converts HeartbeatIndex to repositories.IndexParams+func (input *HeartbeatStore) ToStoreParams(user entities.AuthUser) services.HeartbeatStoreParams {+ return services.HeartbeatStoreParams{+ Owner: input.Owner,+ Timestamp: time.Now().UTC(),+ UserID: user.ID,+ }+}diff --git a/api/pkg/responses/heartbeat_responses.go b/api/pkg/responses/heartbeat_responses.goindex 0ef1e212..f3cfae69 100644--- a/api/pkg/responses/heartbeat_responses.go+++ b/api/pkg/responses/heartbeat_responses.go@@ -7,3 +7,9 @@ type HeartbeatsResponse struct {responseData []entities.Heartbeat `json:"data"`}++// HeartbeatResponse is the payload containing entities.Heartbeat+type HeartbeatResponse struct {+ response+ Data entities.Heartbeat `json:"data"`+}diff --git a/api/pkg/services/heartbeat_service.go b/api/pkg/services/heartbeat_service.goindex 46e46f11..48e2a1ac 100644--- a/api/pkg/services/heartbeat_service.go+++ b/api/pkg/services/heartbeat_service.go@@ -56,7 +56,6 @@ type HeartbeatStoreParams struct {Owner stringTimestamp time.TimeUserID entities.UserID- MessageID uuid.UUID}// Store a new entities.Heartbeat@@ -70,7 +69,6 @@ func (service *HeartbeatService) Store(ctx context.Context, params HeartbeatStorID: uuid.New(),Owner: params.Owner,Timestamp: params.Timestamp,- MessageID: params.MessageID,UserID: params.UserID,}diff --git a/api/pkg/services/message_service.go b/api/pkg/services/message_service.goindex 2adf3ce0..aab11720 100644--- a/api/pkg/services/message_service.go+++ b/api/pkg/services/message_service.go@@ -688,10 +688,6 @@ func (service *MessageService) createMessageSendFailedEvent(source string, payloreturn service.createEvent(events.EventTypeMessageSendFailed, source, payload)}-func (service *MessageService) createHeartbeatPhoneOutstandingEvent(source string, payload events.HeartbeatPhoneOutstandingPayload) (cloudevents.Event, error) {- return service.createEvent(events.EventTypeHeartbeatPhoneOutstanding, source, payload)-}-func (service *MessageService) createMessagePhoneDeliveredEvent(source string, payload events.MessagePhoneDeliveredPayload) (cloudevents.Event, error) {return service.createEvent(events.EventTypeMessagePhoneDelivered, source, payload)}diff --git a/api/pkg/services/notification_service.go b/api/pkg/services/phone_notification_service.gosimilarity index 83%rename from api/pkg/services/notification_service.gorename to api/pkg/services/phone_notification_service.goindex 7b01d4ba..555e01dd 100644--- a/api/pkg/services/notification_service.go+++ b/api/pkg/services/phone_notification_service.go@@ -17,8 +17,8 @@ import ("github.com/palantir/stacktrace")-// NotificationService sends out notifications to mobile phones-type NotificationService struct {+// PhoneNotificationService sends out notifications to mobile phones+type PhoneNotificationService struct {logger telemetry.Loggertracer telemetry.TracerphoneNotificationRepository repositories.PhoneNotificationRepository@@ -27,7 +27,7 @@ type NotificationService struct {eventDispatcher *EventDispatcher}-// NewNotificationService creates a new NotificationService+// NewNotificationService creates a new PhoneNotificationServicefunc NewNotificationService(logger telemetry.Logger,tracer telemetry.Tracer,@@ -35,8 +35,8 @@ func NewNotificationService(phoneRepository repositories.PhoneRepository,phoneNotificationRepository repositories.PhoneNotificationRepository,dispatcher *EventDispatcher,-) (s *NotificationService) {- return &NotificationService{+) (s *PhoneNotificationService) {+ return &PhoneNotificationService{logger: logger.WithService(fmt.Sprintf("%T", s)),tracer: tracer,messagingClient: messagingClient,@@ -46,8 +46,8 @@ func NewNotificationService(}}-// NotificationSendParams are parameters for sending a notification-type NotificationSendParams struct {+// PhoneNotificationSendParams are parameters for sending a notification+type PhoneNotificationSendParams struct {UserID entities.UserIDPhoneID uuid.UUIDPhoneNotificationID uuid.UUID@@ -57,7 +57,7 @@ type NotificationSendParams struct {}// Send sends a message when a message is sent-func (service *NotificationService) Send(ctx context.Context, params *NotificationSendParams) error {+func (service *PhoneNotificationService) Send(ctx context.Context, params *PhoneNotificationSendParams) error {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -84,8 +84,8 @@ func (service *NotificationService) Send(ctx context.Context, params *Notificatireturn service.handleNotificationSent(ctx, phone, result, params)}-// NotificationScheduleParams are parameters for sending a notification-type NotificationScheduleParams struct {+// PhoneNotificationScheduleParams are parameters for sending a notification+type PhoneNotificationScheduleParams struct {UserID entities.UserIDOwner stringSource string@@ -93,7 +93,7 @@ type NotificationScheduleParams struct {}// Schedule a notification to be sent to a phone-func (service *NotificationService) Schedule(ctx context.Context, params *NotificationScheduleParams) error {+func (service *PhoneNotificationService) Schedule(ctx context.Context, params *PhoneNotificationScheduleParams) error {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -134,7 +134,7 @@ func (service *NotificationService) Schedule(ctx context.Context, params *Notifireturn nil}-func (service *NotificationService) handleNotificationFailed(ctx context.Context, err error, params *NotificationSendParams) error {+func (service *PhoneNotificationService) handleNotificationFailed(ctx context.Context, err error, params *PhoneNotificationSendParams) error {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -156,7 +156,7 @@ func (service *NotificationService) handleNotificationFailed(ctx context.Contextreturn nil}-func (service *NotificationService) handleNotificationSent(ctx context.Context, phone *entities.Phone, result string, params *NotificationSendParams) error {+func (service *PhoneNotificationService) handleNotificationSent(ctx context.Context, phone *entities.Phone, result string, params *PhoneNotificationSendParams) error {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -177,7 +177,7 @@ func (service *NotificationService) handleNotificationSent(ctx context.Context,return nil}-func (service *NotificationService) createEvent(source string, notification *entities.PhoneNotification) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createEvent(source string, notification *entities.PhoneNotification) (cloudevents.Event, error) {event := cloudevents.NewEvent()event.SetSource(source)@@ -201,7 +201,7 @@ func (service *NotificationService) createEvent(source string, notification *entreturn event, nil}-func (service *NotificationService) createMessageNotificationSentEvent(source string, phone *entities.Phone, fcmMessageID string, params *NotificationSendParams) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createMessageNotificationSentEvent(source string, phone *entities.Phone, fcmMessageID string, params *PhoneNotificationSendParams) (cloudevents.Event, error) {event := cloudevents.NewEvent()event.SetSource(source)@@ -228,7 +228,7 @@ func (service *NotificationService) createMessageNotificationSentEvent(source streturn event, nil}-func (service *NotificationService) createMessageNotificationFailedEvent(source string, errorMessage string, params *NotificationSendParams) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createMessageNotificationFailedEvent(source string, errorMessage string, params *PhoneNotificationSendParams) (cloudevents.Event, error) {event := cloudevents.NewEvent()event.SetSource(source)@@ -253,7 +253,7 @@ func (service *NotificationService) createMessageNotificationFailedEvent(sourcereturn event, nil}-func (service *NotificationService) updateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) {+func (service *PhoneNotificationService) updateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) {ctx, span := service.tracer.Start(ctx)defer span.End()diff --git a/api/pkg/validators/heartbeat_handler_validator.go b/api/pkg/validators/heartbeat_handler_validator.goindex 063af6b3..6811dfd0 100644--- a/api/pkg/validators/heartbeat_handler_validator.go+++ b/api/pkg/validators/heartbeat_handler_validator.go@@ -56,3 +56,17 @@ func (validator *HeartbeatHandlerValidator) ValidateIndex(_ context.Context, req})return v.ValidateStruct()}++// ValidateStore validates the requests.HeartbeatStore request+func (validator *HeartbeatHandlerValidator) ValidateStore(_ context.Context, request requests.HeartbeatStore) url.Values {+ v := govalidator.New(govalidator.Options{+ Data: &request,+ Rules: govalidator.MapData{+ "owner": []string{+ "required",+ phoneNumberRule,+ },+ },+ })+ return v.ValidateStruct()+}