Skip to content

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

Update newsletter email settings

Acho Arnold880f518f4b9d
diff --git a/api/.gitignore b/api/.gitignore
index 78b2e765..19bdf4df 100644
--- a/api/.gitignore
+++ b/api/.gitignore
@@ -8,3 +8,4 @@ $path
!.env.project
!.env.vault
!.env.docker
+cmd/experiments/*
diff --git a/api/cmd/experiments/main.go b/api/cmd/experiments/main.go
deleted file mode 100644
index f6204e7a..00000000
--- a/api/cmd/experiments/main.go
+++ /dev/null
@@ -1,194 +0,0 @@
-package main
-
-import (
- "bytes"
- "context"
- "encoding/csv"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "log"
- "net/http"
- "os"
- "strings"
- "sync"
- "time"
-
- "firebase.google.com/go/auth"
- "github.com/NdoleStudio/httpsms/pkg/telemetry"
- "google.golang.org/api/iterator"
-
- "github.com/palantir/stacktrace"
-
- "github.com/NdoleStudio/httpsms/pkg/di"
- "github.com/NdoleStudio/httpsms/pkg/entities"
- "github.com/google/uuid"
-
- "github.com/carlmjohnson/requests"
-
- "github.com/joho/godotenv"
-)
-
-func main() {
- err := godotenv.Load("../../.env")
- if err != nil {
- log.Fatal("Error loading .env file")
- }
-
- container := di.NewLiteContainer()
- logger := container.Logger()
-
- authClient := container.FirebaseAuthClient()
-
- var users []*auth.ExportedUserRecord
- iter := authClient.Users(context.Background(), "")
- for {
- user, err := iter.Next()
- if errors.Is(err, iterator.Done) {
- break
- }
- if err != nil {
- logger.Fatal(err)
- }
- users = append(users, user)
- }
-
- logger.Info(fmt.Sprintf("fetched %d users", len(users)))
- exportUsers(logger, users)
-
- logger.Info("Starting experiments")
-}
-
-func exportUsers(logger telemetry.Logger, users []*auth.ExportedUserRecord) {
- records := [][]string{
- {"First name", "Email address", "External ID"},
- }
-
- for _, user := range users {
- records = append(records, []string{user.UserInfo.DisplayName, user.UserInfo.Email, user.UserInfo.UID})
- }
-
- file, err := os.Create("result.csv")
- if err != nil {
- logger.Fatal(stacktrace.Propagate(err, "cannot create file"))
- }
-
- w := csv.NewWriter(file)
- if err = w.WriteAll(records); err != nil {
- logger.Fatal(stacktrace.Propagate(err, "cannot write csv"))
- }
-}
-
-func chunkBy[T any](items []T, chunkSize int) (chunks [][]T) {
- for chunkSize < len(items) {
- items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])
- }
- return append(chunks, items)
-}
-
-func deleteContacts(container *di.Container) {
- sendgrid := container.MarketingService()
- logger := container.Logger()
-
- b, err := os.ReadFile("28462979_873d41e1-cd34-4782-8992-0762ed247667.csv") // just pass the file name
- if err != nil {
- logger.Fatal(stacktrace.Propagate(err, "cannot read file"))
- }
-
- lines := strings.Split(string(b), "\n")[1:]
- var contacts []string
- for _, line := range lines {
- if len(line) >= 17 {
- contacts = append(contacts, strings.ReplaceAll(strings.Split(line, ",")[17], "\"", ""))
- }
- }
-
- chunks := chunkBy(contacts, 100)
- for _, chunk := range chunks {
- err = sendgrid.DeleteContacts(context.Background(), chunk)
- if err != nil {
- logger.Fatal(err)
- }
- }
-}
-
-func text3CX() {
- container := di.NewLiteContainer()
- repo := container.Integration3CXRepository()
-
- err := repo.Save(context.Background(), &entities.Integration3CX{
- ID: uuid.MustParse("b0b1acdc-69dd-4aee-8277-ba4adc5d2e90"),
- UserID: "XtABz6zdeFMoBLoltz6SREDvRSh2",
- WebhookURL: "https://lagomtest.3cx.com.au/sms/generic/155e125bf7874f8fae5adbcaac49fdf8",
- CreatedAt: time.Now().UTC(),
- UpdatedAt: time.Now().UTC(),
- })
- if err != nil {
- container.Logger().Fatal(err)
- }
-}
-
-func loadTest() {
- wg := sync.WaitGroup{}
- for i := 0; i < 1; i++ {
- wg.Add(1)
- go func(count int) {
- sendSMS(fmt.Sprintf("[%d] In the quiet of the night, the stars above whisper secrets of the universe. We, mere stardust, seek meaning in their cosmic dance, yearning to unlock the mysteries of existence that stretch far beyond our earthly bounds.", count))
- wg.Done()
- }(i)
-
- }
- wg.Wait()
-}
-
-func sendSingle() {
- payload, err := json.Marshal(map[string]any{
- "content": fmt.Sprintf("This is a test text message"),
- "from": os.Getenv("HTTPSMS_FROM"),
- "to": os.Getenv("HTTPSMS_TO"),
- "encrypted": false,
- })
- if err != nil {
- log.Fatal(stacktrace.Propagate(err, "cannot marshal payload"))
- }
-
- req, err := http.NewRequest(http.MethodGet, "https://api.httpsms.com/v1/messages/send", bytes.NewBuffer(payload))
- if err != nil {
- log.Fatal(stacktrace.Propagate(err, "cannot create request"))
- }
-
- req.Header.Add("x-api-key", os.Getenv("HTTPSMS_KEY"))
-
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- log.Fatal(stacktrace.Propagate(err, "cannot send request"))
- }
-
- fmt.Printf("client: got response!\n")
- fmt.Printf("client: status code: %d\n", res.StatusCode)
-
- resBody, err := io.ReadAll(res.Body)
- if err != nil {
- log.Fatal(stacktrace.Propagate(err, "could not read response body"))
- }
-
- fmt.Printf("client: response body: %s\n", resBody)
-}
-
-func sendSMS(content string) {
- var response string
- err := requests.URL(os.Getenv("BASIC_URL")).
- BodyJSON(map[string]any{
- "content": content,
- "from": os.Getenv("BASIC_FROM"),
- "to": os.Getenv("BASIC_TO"),
- }).
- BasicAuth(os.Getenv("BASIC_USERNAME"), os.Getenv("BASIC_PASSWORD")).
- ToString(&response).
- Fetch(context.Background())
- if err != nil {
- log.Fatal(err)
- }
- log.Printf("%s\n", response)
-}
diff --git a/api/pkg/entities/user.go b/api/pkg/entities/user.go
index aff66c53..ff560ad0 100644
--- a/api/pkg/entities/user.go
+++ b/api/pkg/entities/user.go
@@ -85,6 +85,7 @@ type User struct {
NotificationMessageStatusEnabled bool `json:"notification_message_status_enabled" gorm:"default:true" example:"true"`
NotificationWebhookEnabled bool `json:"notification_webhook_enabled" gorm:"default:true" example:"true"`
NotificationHeartbeatEnabled bool `json:"notification_heartbeat_enabled" gorm:"default:true" example:"true"`
+ NotificationNewsletterEnabled bool `json:"notification_newsletter_enabled" gorm:"default:true" example:"true"`
CreatedAt time.Time `json:"created_at" example:"2022-06-05T14:26:02.302718+03:00"`
UpdatedAt time.Time `json:"updated_at" example:"2022-06-05T14:26:10.303278+03:00"`
}
diff --git a/api/pkg/requests/user_notification_update_request.go b/api/pkg/requests/user_notification_update_request.go
index e84e57a8..b8b92a54 100644
--- a/api/pkg/requests/user_notification_update_request.go
+++ b/api/pkg/requests/user_notification_update_request.go
@@ -10,6 +10,7 @@ type UserNotificationUpdate struct {
MessageStatusEnabled bool `json:"message_status_enabled" example:"true"`
WebhookEnabled bool `json:"webhook_enabled" example:"true"`
HeartbeatEnabled bool `json:"heartbeat_enabled" example:"true"`
+ NewsletterEnabled bool `json:"newsletter_enabled" example:"true"`
}
// ToUserNotificationUpdateParams converts UserNotificationUpdate to services.UserNotificationUpdateParams
@@ -18,5 +19,6 @@ func (input *UserNotificationUpdate) ToUserNotificationUpdateParams() *services.
MessageStatusEnabled: input.MessageStatusEnabled,
WebhookEnabled: input.WebhookEnabled,
HeartbeatEnabled: input.HeartbeatEnabled,
+ NewsletterEnabled: input.NewsletterEnabled,
}
}
diff --git a/api/pkg/services/user_service.go b/api/pkg/services/user_service.go
index 0bebcb95..78eca44c 100644
--- a/api/pkg/services/user_service.go
+++ b/api/pkg/services/user_service.go
@@ -131,6 +131,7 @@ type UserNotificationUpdateParams struct {
MessageStatusEnabled bool
WebhookEnabled bool
HeartbeatEnabled bool
+ NewsletterEnabled bool
}
// UpdateNotificationSettings for an entities.User
@@ -147,6 +148,7 @@ func (service *UserService) UpdateNotificationSettings(ctx context.Context, user
user.NotificationWebhookEnabled = params.WebhookEnabled
user.NotificationHeartbeatEnabled = params.HeartbeatEnabled
user.NotificationMessageStatusEnabled = params.MessageStatusEnabled
+ user.NotificationNewsletterEnabled = params.NewsletterEnabled
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("cannot save user with id [%s] in [%T]", user.ID, service.repository)
diff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vue
index e0f663af..10cbf94f 100644
--- a/web/pages/settings/index.vue
+++ b/web/pages/settings/index.vue
@@ -399,6 +399,13 @@
hint="This switch controls email notifications we send when we your message is failed or expired."
persistent-hint
></v-switch>
+ <v-switch
+ v-model="notificationSettings.newsletter_enabled"
+ label="Newsletter emails"
+ :disabled="updatingEmailNotifications"
+ hint="This switch controls newsletter emails about new features, updates, and promotions."
+ persistent-hint
+ ></v-switch>
<v-btn
color="primary"
:loading="updatingEmailNotifications"
@@ -870,6 +877,7 @@ export default Vue.extend({
notificationSettings: {
webhook_enabled: true,
message_status_enabled: true,
+ newsletter_enabled: true,
heartbeat_enabled: true,
},
updatingWebhook: false,
@@ -965,6 +973,8 @@ export default Vue.extend({
this.$store.getters.getUser.notification_message_status_enabled,
heartbeat_enabled:
this.$store.getters.getUser.notification_heartbeat_enabled,
+ newsletter_enabled:
+ this.$store.getters.getUser.notification_newsletter_enabled,
}
},
showEditPhone(phoneId) {