Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
Add api to archive messages
Acho Arnold2bdd0314093d
diff --git a/api/pkg/entities/message_thread.go b/api/pkg/entities/message_thread.goindex 47de8416..f30d39b1 100644--- a/api/pkg/entities/message_thread.go+++ b/api/pkg/entities/message_thread.go@@ -28,3 +28,9 @@ func (thread *MessageThread) Update(timestamp time.Time, messageID uuid.UUID, cothread.LastMessageContent = contentreturn thread}++// UpdateArchive sets a message thread as archived+func (thread *MessageThread) UpdateArchive(isArchived bool) *MessageThread {+ thread.IsArchived = isArchived+ return thread+}diff --git a/api/pkg/handlers/message_handler.go b/api/pkg/handlers/message_handler.goindex 7ad44c7d..96e3da47 100644--- a/api/pkg/handlers/message_handler.go+++ b/api/pkg/handlers/message_handler.go@@ -77,7 +77,7 @@ func (h *MessageHandler) PostSend(c *fiber.Ctx) error {return h.responseBadRequest(c, err)}- if errors := h.validator.ValidateMessageSend(ctx, request); len(errors) != 0 {+ if errors := h.validator.ValidateMessageSend(ctx, request.Sanitize()); len(errors) != 0 {msg := fmt.Sprintf("validation errors [%s], while sending payload [%s]", spew.Sdump(errors), c.Body())ctxLogger.Warn(stacktrace.NewError(msg))return h.responseUnprocessableEntity(c, errors, "validation errors while sending message")@@ -269,7 +269,7 @@ func (h *MessageHandler) PostReceive(c *fiber.Ctx) error {return h.responseBadRequest(c, err)}- if errors := h.validator.ValidateMessageReceive(ctx, request); len(errors) != 0 {+ if errors := h.validator.ValidateMessageReceive(ctx, request.Sanitize()); len(errors) != 0 {msg := fmt.Sprintf("validation errors [%s], while sending payload [%s]", spew.Sdump(errors), c.Body())ctxLogger.Warn(stacktrace.NewError(msg))return h.responseUnprocessableEntity(c, errors, "validation errors while receiving message")diff --git a/api/pkg/handlers/message_thread_handler.go b/api/pkg/handlers/message_thread_handler.goindex 527d6b19..6ee83504 100644--- a/api/pkg/handlers/message_thread_handler.go+++ b/api/pkg/handlers/message_thread_handler.go@@ -39,6 +39,7 @@ func NewMessageThreadHandler(// RegisterRoutes registers the routes for the MessageHandlerfunc (h *MessageThreadHandler) RegisterRoutes(router fiber.Router) {router.Get("/message-threads", h.Index)+ router.Put("/message-threads/:messageThreadID", h.Update)}// Index returns message threads for a phone number@@ -88,3 +89,46 @@ func (h *MessageThreadHandler) Index(c *fiber.Ctx) error {return h.responseOK(c, fmt.Sprintf("fetched %d message %s", len(*threads), h.pluralize("thread", len(*threads))), threads)}++// Update an entities.MessageThread+// @Summary Update a message thread+// @Description Updates the details of a message thread+// @Security ApiKeyAuth+// @Tags Message Threads+// @Accept json+// @Produce json+// @Param payload body requests.MessageThreadUpdate true "Payload of message thread details to update"+// @Success 200 {object} responses.PhoneResponse+// @Failure 400 {object} responses.BadRequest+// @Failure 401 {object} responses.Unauthorized+// @Failure 422 {object} responses.UnprocessableEntity+// @Failure 500 {object} responses.InternalServerError+// @Router /message-threads/{messageThreadID} [put]+func (h *MessageThreadHandler) Update(c *fiber.Ctx) error {+ ctx, span := h.tracer.StartFromFiberCtx(c)+ defer span.End()++ ctxLogger := h.tracer.CtxLogger(h.logger, span)++ var request requests.MessageThreadUpdate+ if err := c.BodyParser(&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.ValidateUpdate(ctx, request); len(errors) != 0 {+ msg := fmt.Sprintf("validation errors [%s], while updating message thread [%+#v]", spew.Sdump(errors), request)+ ctxLogger.Warn(stacktrace.NewError(msg))+ return h.responseUnprocessableEntity(c, errors, "validation errors while updating message thread")+ }++ thread, err := h.service.UpdateStatus(ctx, request.ToUpdateParams())+ if err != nil {+ msg := fmt.Sprintf("cannot update message thread with params [%+#v]", request)+ ctxLogger.Error(stacktrace.Propagate(err, msg))+ return h.responseInternalServerError(c)+ }++ return h.responseOK(c, "message thread updated successfully", thread)+}diff --git a/api/pkg/handlers/user_handler.go b/api/pkg/handlers/user_handler.goindex c25947df..2c44dda7 100644--- a/api/pkg/handlers/user_handler.go+++ b/api/pkg/handlers/user_handler.go@@ -78,7 +78,7 @@ func (h *UserHandler) Show(c *fiber.Ctx) error {// @Summary Update a user// @Description Updates the details of the currently authenticated user// @Security ApiKeyAuth-// @Tags Phones+// @Tags Users// @Accept json// @Produce json// @Param payload body requests.UserUpdate true "Payload of user details to update"@@ -104,7 +104,7 @@ func (h *UserHandler) Update(c *fiber.Ctx) error {if errors := h.validator.ValidateUpdate(ctx, request.Sanitize()); len(errors) != 0 {msg := fmt.Sprintf("validation errors [%s], while updating user [%+#v]", spew.Sdump(errors), request)ctxLogger.Warn(stacktrace.NewError(msg))- return h.responseUnprocessableEntity(c, errors, "validation errors while fetching phones")+ return h.responseUnprocessableEntity(c, errors, "validation errors while updating user")}user, err := h.service.Update(ctx, h.userFromContext(c), request.ToUpdateParams())diff --git a/api/pkg/repositories/gorm_message_thread_repository.go b/api/pkg/repositories/gorm_message_thread_repository.goindex d75132cd..751f5524 100644--- a/api/pkg/repositories/gorm_message_thread_repository.go+++ b/api/pkg/repositories/gorm_message_thread_repository.go@@ -60,7 +60,7 @@ func (repository *gormMessageThreadRepository) Update(ctx context.Context, threa}// Load a thread between 2 users-func (repository *gormMessageThreadRepository) Load(ctx context.Context, owner string, contact string) (*entities.MessageThread, error) {+func (repository *gormMessageThreadRepository) LoadByOwnerContact(ctx context.Context, owner string, contact string) (*entities.MessageThread, error) {ctx, span := repository.tracer.Start(ctx)defer span.End()diff --git a/api/pkg/repositories/message_thread_repository.go b/api/pkg/repositories/message_thread_repository.goindex 5984da21..fbbeedda 100644--- a/api/pkg/repositories/message_thread_repository.go+++ b/api/pkg/repositories/message_thread_repository.go@@ -3,6 +3,8 @@ package repositoriesimport ("context"+ "github.com/google/uuid"+"github.com/NdoleStudio/http-sms-manager/pkg/entities")@@ -14,9 +16,12 @@ type MessageThreadRepository interface {// Update a new entities.MessageThreadUpdate(ctx context.Context, thread *entities.MessageThread) error- // Load a thread between 2 users- Load(ctx context.Context, owner string, contact string) (*entities.MessageThread, error)+ // LoadByOwnerContact fetches a thread between owner and contact+ LoadByOwnerContact(ctx context.Context, owner string, contact string) (*entities.MessageThread, error)++ // Load a thread by ID+ Load(ctx context.Context, ID uuid.UUID) (*entities.MessageThread, error)// Index message threads for an owner- Index(ctx context.Context, owner string, params IndexParams) (*[]entities.MessageThread, error)+ Index(ctx context.Context, owner string, archived bool, params IndexParams) (*[]entities.MessageThread, error)}diff --git a/api/pkg/requests/message_thread_update_request.go b/api/pkg/requests/message_thread_update_request.gonew file mode 100644index 00000000..216eb70f--- /dev/null+++ b/api/pkg/requests/message_thread_update_request.go@@ -0,0 +1,23 @@+package requests++import (+ "github.com/google/uuid"++ "github.com/NdoleStudio/http-sms-manager/pkg/services"+)++// MessageThreadUpdate is the payload for updating a message thread+type MessageThreadUpdate struct {+ request+ IsArchived bool `json:"is_archived" example:"true"`++ MessageThreadID string `json:"messageThreadID" swaggerignore:"true"` // used internally for validation+}++// ToUpdateParams converts MessageThreadUpdate to services.MessageThreadStatusParams+func (input *MessageThreadUpdate) ToUpdateParams() services.MessageThreadStatusParams {+ return services.MessageThreadStatusParams{+ MessageThreadID: uuid.MustParse(input.MessageThreadID),+ IsArchived: input.IsArchived,+ }+}diff --git a/api/pkg/services/message_thread_service.go b/api/pkg/services/message_thread_service.goindex 77866712..d142c75f 100644--- a/api/pkg/services/message_thread_service.go+++ b/api/pkg/services/message_thread_service.go@@ -49,7 +49,7 @@ func (service *MessageThreadService) UpdateThread(ctx context.Context, params MectxLogger := service.tracer.CtxLogger(service.logger, span)- thread, err := service.repository.Load(ctx, params.Owner, params.Contact)+ thread, err := service.repository.LoadByOwnerContact(ctx, params.Owner, params.Contact)if err != nil && stacktrace.GetCode(err) == repositories.ErrCodeNotFound {ctxLogger.Info(fmt.Sprintf("cannot find thread with owner [%s], and contact [%s]. creating new thread", params.Owner, params.Contact))return service.createThread(ctx, params)@@ -74,6 +74,34 @@ func (service *MessageThreadService) UpdateThread(ctx context.Context, params Mereturn nil}+// MessageThreadStatusParams are parameters for updating a thread status+type MessageThreadStatusParams struct {+ IsArchived bool+ MessageThreadID uuid.UUID+}++// UpdateStatus updates a thread between an owner and a contact+func (service *MessageThreadService) UpdateStatus(ctx context.Context, params MessageThreadStatusParams) (*entities.MessageThread, error) {+ ctx, span := service.tracer.Start(ctx)+ defer span.End()++ ctxLogger := service.tracer.CtxLogger(service.logger, span)++ thread, err := service.repository.Load(ctx, params.MessageThreadID)+ if err != nil {+ msg := fmt.Sprintf("cannot find thread with id [%s]", params.MessageThreadID)+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ }++ if err = service.repository.Update(ctx, thread.UpdateArchive(params.IsArchived)); err != nil {+ msg := fmt.Sprintf("cannot update message thread with id [%s] with archive status [%t]", thread.ID, params.IsArchived)+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ }++ ctxLogger.Info(fmt.Sprintf("thread with id [%s] updated with archive status [%t]", thread.ID, thread.IsArchived))+ return thread, nil+}+func (service *MessageThreadService) createThread(ctx context.Context, params MessageThreadUpdateParams) error {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -134,7 +162,8 @@ func (service *MessageThreadService) getColor() string {// MessageThreadGetParams parameters fetching threadstype MessageThreadGetParams struct {repositories.IndexParams- Owner string+ IsArchived bool+ Owner string}// GetThreads fetches threads for an owner@@ -144,7 +173,7 @@ func (service *MessageThreadService) GetThreads(ctx context.Context, params MessctxLogger := service.tracer.CtxLogger(service.logger, span)- threads, err := service.repository.Index(ctx, params.Owner, params.IndexParams)+ threads, err := service.repository.Index(ctx, params.Owner, params.IsArchived, params.IndexParams)if err != nil {msg := fmt.Sprintf("could not fetch messages threads for params [%+#v]", params)return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))diff --git a/api/pkg/validators/message_thread_handler_validator.go b/api/pkg/validators/message_thread_handler_validator.goindex 7107d9cb..349044df 100644--- a/api/pkg/validators/message_thread_handler_validator.go+++ b/api/pkg/validators/message_thread_handler_validator.go@@ -55,3 +55,18 @@ func (validator *MessageThreadHandlerValidator) ValidateMessageThreadIndex(_ con})return v.ValidateStruct()}++// ValidateUpdate validates requests.UserUpdate+func (validator *MessageThreadHandlerValidator) ValidateUpdate(_ context.Context, request requests.MessageThreadUpdate) url.Values {+ v := govalidator.New(govalidator.Options{+ Data: &request,+ Rules: govalidator.MapData{+ "messageThreadID": []string{+ "required",+ "uuid",+ },+ },+ })++ return v.ValidateStruct()+}