Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Send email when a message fails or is expired

Acho Arnoldd8c662c34136
diff --git a/api/pkg/emails/hermes_notification_email_factory.go b/api/pkg/emails/hermes_notification_email_factory.go
new file mode 100644
index 00000000..dbb20b2c
--- /dev/null
+++ b/api/pkg/emails/hermes_notification_email_factory.go
@@ -0,0 +1,124 @@
+package emails
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+ "github.com/matcornic/hermes/v2"
+ "github.com/palantir/stacktrace"
+)
+
+type hermesNotificationEmailFactory struct {
+ config *HermesGeneratorConfig
+ generator hermes.Hermes
+}
+
+// NewHermesNotificationEmailFactory creates a new instance of the UserEmailFactory
+func NewHermesNotificationEmailFactory(config *HermesGeneratorConfig) NotificationEmailFactory {
+ return &hermesNotificationEmailFactory{
+ config: config,
+ generator: config.Generator(),
+ }
+}
+
+func (factory *hermesNotificationEmailFactory) MessageExpired(user *entities.User, messageID uuid.UUID, owner string, contact string, content string) (*Email, error) {
+ email := hermes.Email{
+ Body: hermes.Body{
+ Title: "Hello",
+ Intros: []string{
+ fmt.Sprintf("The SMS message which you sent to %s has expired at %s and you will need to resend this message.", owner, user.UserTimeString(time.Now())),
+ },
+ Dictionary: []hermes.Entry{
+ {"ID", messageID.String()},
+ {"From", owner},
+ {"To", contact},
+ {"Message", content},
+ },
+ Actions: []hermes.Action{
+ {
+ Instructions: "Messages expire because we couldn't connect with your mobile phone to send the outgoing SMS. You can fix this by making sure your phone is connected to the internet and also connect your phone to the charger all the time since Android may kill the httpSMS app if it has been active for a very long time so save phone battery.",
+ Button: hermes.Button{
+ Color: "#329ef4",
+ TextColor: "#FFFFFF",
+ Text: "View Messages",
+ Link: "https://httpsms.com/threads",
+ },
+ },
+ },
+ Signature: "Cheers",
+ Outros: []string{
+ fmt.Sprintf("Don't hesitate to contact us by replying to this email."),
+ },
+ },
+ }
+
+ html, err := factory.generator.GenerateHTML(email)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "cannot generate html email")
+ }
+
+ text, err := factory.generator.GeneratePlainText(email)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "cannot generate text email")
+ }
+
+ return &Email{
+ ToEmail: user.Email,
+ Subject: "🔔 Your SMS message has expired on httpSMS",
+ HTML: html,
+ Text: text,
+ }, nil
+}
+
+func (factory *hermesNotificationEmailFactory) MessageFailed(user *entities.User, messageID uuid.UUID, owner, contact, content, reason string) (*Email, error) {
+ email := hermes.Email{
+ Body: hermes.Body{
+ Title: "Hello",
+ Intros: []string{
+ fmt.Sprintf("The SMS message which you sent to %s has failed at %s and you will need to resend this message.", owner, user.UserTimeString(time.Now())),
+ },
+ Dictionary: []hermes.Entry{
+ {"ID", messageID.String()},
+ {"From", owner},
+ {"To", contact},
+ {"Message", content},
+ {"Failure Reason", reason},
+ },
+ Actions: []hermes.Action{
+ {
+ Instructions: "Check the default SMS messaging app on your phone to find out the exact reason why the message failed. Usually messages fail because the httpSMS app phone has been un-installed or it is not active. Logout and login again on the mobile app on your Android phone and retry sending the SMS.",
+ Button: hermes.Button{
+ Color: "#329ef4",
+ TextColor: "#FFFFFF",
+ Text: "View Messages",
+ Link: "https://httpsms.com/threads",
+ },
+ },
+ },
+ Signature: "Cheers",
+ Outros: []string{
+ fmt.Sprintf("Don't hesitate to contact us by replying to this email."),
+ },
+ },
+ }
+
+ html, err := factory.generator.GenerateHTML(email)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "cannot generate html email")
+ }
+
+ text, err := factory.generator.GeneratePlainText(email)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "cannot generate text email")
+ }
+
+ return &Email{
+ ToEmail: user.Email,
+ Subject: "⚡ Your SMS message has failed on httpSMS",
+ HTML: html,
+ Text: text,
+ }, nil
+}
diff --git a/api/pkg/emails/notification_email_factory.go b/api/pkg/emails/notification_email_factory.go
index 82a519fa..0081707d 100644
--- a/api/pkg/emails/notification_email_factory.go
+++ b/api/pkg/emails/notification_email_factory.go
@@ -1,4 +1,15 @@
package emails
+import (
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+ "github.com/google/uuid"
+)
+
// NotificationEmailFactory generates emails to users about a message
-type NotificationEmailFactory interface{}
+type NotificationEmailFactory interface {
+ // MessageExpired sends an email when the user's message is expired
+ MessageExpired(user *entities.User, messageID uuid.UUID, owner, contact, content string) (*Email, error)
+
+ // MessageFailed sends an email when the user's message is failed
+ MessageFailed(user *entities.User, messageID uuid.UUID, owner, contact, content, reason string) (*Email, error)
+}
diff --git a/api/pkg/entities/user.go b/api/pkg/entities/user.go
index 4716425c..a988d850 100644
--- a/api/pkg/entities/user.go
+++ b/api/pkg/entities/user.go
@@ -80,3 +80,12 @@ func (user User) IsOnProPlan() bool {
func (user User) IsOnUltraPlan() bool {
return user.SubscriptionName == SubscriptionNameUltraMonthly || user.SubscriptionName == SubscriptionNameUltraYearly
}
+
+// UserTimeString converts the time to the user's timezone
+func (user User) UserTimeString(timestamp time.Time) string {
+ location, err := time.LoadLocation(user.Timezone)
+ if err != nil {
+ location = time.UTC
+ }
+ return timestamp.In(location).Format(time.RFC1123)
+}
diff --git a/api/pkg/events/message_send_expired_event.go b/api/pkg/events/message_send_expired_event.go
index afaba6a1..697deadd 100644
--- a/api/pkg/events/message_send_expired_event.go
+++ b/api/pkg/events/message_send_expired_event.go
@@ -16,6 +16,7 @@ type MessageSendExpiredPayload struct {
MessageID uuid.UUID `json:"message_id"`
Owner string `json:"owner"`
SendAttemptCount uint `json:"send_attempt_count"`
+ IsFinal bool `json:"is_final"`
RequestID *string `json:"request_id"`
Contact string `json:"contact"`
UserID entities.UserID `json:"user_id"`
diff --git a/api/pkg/repositories/gorm_user_repository.go b/api/pkg/repositories/gorm_user_repository.go
index 58e39fd7..0c79405f 100644
--- a/api/pkg/repositories/gorm_user_repository.go
+++ b/api/pkg/repositories/gorm_user_repository.go
@@ -187,9 +187,8 @@ func (repository *gormUserRepository) LoadOrStore(ctx context.Context, authUser
// case the caller should not continue.
func (repository *gormUserRepository) generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
- _, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
- if err != nil {
+ if _, err := rand.Read(b); err != nil {
return nil, stacktrace.Propagate(err, fmt.Sprintf("cannot generate [%d] random bytes", n))
}
diff --git a/api/pkg/services/billing_service.go b/api/pkg/services/billing_service.go
index e38f7ba0..c9a19974 100644
--- a/api/pkg/services/billing_service.go
+++ b/api/pkg/services/billing_service.go
@@ -111,11 +111,11 @@ func (service *BillingService) sendLimitExceededEmail(ctx context.Context, user
if err = service.mailer.Send(ctx, email); err != nil {
msg := fmt.Sprintf("canot send usage limit exceeded notification to user [%s]", user.ID)
ctxLogger.Error(stacktrace.Propagate(err, msg))
+ return
}
ctxLogger.Info(fmt.Sprintf("usage limit exceeded email sent to user [%s]", user.ID))
-
- if err = service.cache.Set(ctx, key, "", time.Hour); err != nil {
+ if err = service.cache.Set(ctx, key, "", time.Hour*12); err != nil {
ctxLogger.Error(stacktrace.Propagate(err, fmt.Sprintf("cannot set item in redis with key [%s]", key)))
}
}
diff --git a/api/pkg/services/email_notification_service.go b/api/pkg/services/email_notification_service.go
index 1e960c7b..cca38ee7 100644
--- a/api/pkg/services/email_notification_service.go
+++ b/api/pkg/services/email_notification_service.go
@@ -3,6 +3,9 @@ package services
import (
"context"
"fmt"
+ "time"
+
+ "github.com/palantir/stacktrace"
"github.com/NdoleStudio/httpsms/pkg/cache"
"github.com/NdoleStudio/httpsms/pkg/emails"
@@ -43,10 +46,90 @@ func NewEmailNotificationService(
// NotifyMessageExpired sends an email to the user about an expired message
func (service *EmailNotificationService) NotifyMessageExpired(ctx context.Context, payload *events.MessageSendExpiredPayload) error {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ if !payload.IsFinal {
+ ctxLogger.Info(fmt.Sprintf("[%s] event is not final, send attempt count = [%d]", events.EventTypeMessageSendExpired, payload.SendAttemptCount))
+ return nil
+ }
+
+ if !service.canSendEmail(ctx, events.EventTypeMessageSendExpired, payload.Owner) {
+ ctxLogger.Info(fmt.Sprintf("[%s] email already sent to user [%s] with owner [%s]", events.EventTypeMessageSendExpired, payload.UserID, payload.Owner))
+ return nil
+ }
+
+ user, err := service.userRepository.Load(ctx, payload.UserID)
+ if err != nil {
+ msg := fmt.Sprintf("cannot load user with ID [%s] and for expired message with ID [%s]", payload.UserID, payload.MessageID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))
+ }
+
+ email, err := service.factory.MessageExpired(user, payload.MessageID, payload.Owner, payload.Contact, payload.Content)
+ if err != nil {
+ msg := fmt.Sprintf("cannot create email for user with ID [%s] and for expired message with ID [%s]", payload.UserID, payload.MessageID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ if err = service.mailer.Send(ctx, email); err != nil {
+ msg := fmt.Sprintf("cannot send email for user with ID [%s] and for expired message with ID [%s]", payload.UserID, payload.MessageID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ ctxLogger.Info(fmt.Sprintf("[%s] email sent to [%s] for message with ID [%s]", events.EventTypeMessageSendExpired, user.ID, payload.MessageID))
+
+ service.addToCache(ctx, events.EventTypeMessageSendExpired, payload.Owner)
return nil
}
// NotifyMessageFailed sends an email to the user about a failed message
func (service *EmailNotificationService) NotifyMessageFailed(ctx context.Context, payload *events.MessageSendFailedPayload) error {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ if !service.canSendEmail(ctx, events.EventTypeMessageSendFailed, payload.Owner) {
+ ctxLogger.Info(fmt.Sprintf("[%s] email already sent to user [%s] with owner [%s]", events.EventTypeMessageSendFailed, payload.UserID, payload.Owner))
+ return nil
+ }
+
+ user, err := service.userRepository.Load(ctx, payload.UserID)
+ if err != nil {
+ msg := fmt.Sprintf("cannot load user with ID [%s] for [%s] message with ID [%s]", payload.UserID, payload.ID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))
+ }
+
+ email, err := service.factory.MessageFailed(user, payload.ID, payload.Owner, payload.Contact, payload.Content, payload.ErrorMessage)
+ if err != nil {
+ msg := fmt.Sprintf("cannot create email for user with ID [%s] for [%s] message with ID [%s]", payload.UserID, payload.ID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ if err = service.mailer.Send(ctx, email); err != nil {
+ msg := fmt.Sprintf("cannot send email for user with ID [%s] for [%s] message with ID [%s]", payload.UserID, events.EventTypeMessageSendFailed, payload.ID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ ctxLogger.Info(fmt.Sprintf("[%s] email sent to [%s] for message with ID [%s]", events.EventTypeMessageSendFailed, user.ID, payload.ID))
+
+ service.addToCache(ctx, events.EventTypeMessageSendFailed, payload.Owner)
return nil
}
+
+func (service *EmailNotificationService) getCacheKey(event string, owner string) string {
+ return fmt.Sprintf("email.%s.%s", event, owner)
+}
+
+func (service *EmailNotificationService) canSendEmail(ctx context.Context, event string, owner string) bool {
+ _, err := service.cache.Get(ctx, service.getCacheKey(event, owner))
+ return err != nil
+}
+
+func (service *EmailNotificationService) addToCache(ctx context.Context, event string, owner string) {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ cacheKey := service.getCacheKey(event, owner)
+ if err := service.cache.Set(ctx, cacheKey, "", time.Minute*15); err != nil {
+ ctxLogger.Error(stacktrace.Propagate(err, fmt.Sprintf("cannot set item in redis with key [%s] for owner [%s]", cacheKey, owner)))
+ }
+}
diff --git a/api/pkg/services/message_service.go b/api/pkg/services/message_service.go
index 8ad1795b..fd64afbe 100644
--- a/api/pkg/services/message_service.go
+++ b/api/pkg/services/message_service.go
@@ -672,6 +672,7 @@ func (service *MessageService) CheckExpired(ctx context.Context, params MessageC
Owner: message.Owner,
Contact: message.Contact,
RequestID: message.RequestID,
+ IsFinal: message.SendAttemptCount == message.MaxSendAttempts,
SendAttemptCount: message.SendAttemptCount,
UserID: message.UserID,
Timestamp: time.Now().UTC(),