Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
Fix fetching of outstanding messages
Acho Arnold5e3fe3972620
diff --git a/android/app/build.gradle b/android/app/build.gradleindex 5a1d4fde..afdfcd1e 100644--- a/android/app/build.gradle+++ b/android/app/build.gradle@@ -37,6 +37,7 @@ android {kotlinOptions {jvmTarget = '1.8'}+ namespace 'com.httpsms'}dependencies {diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 15a09923..237e8ca9 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -1,7 +1,6 @@<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:tools="http://schemas.android.com/tools"- package="com.httpsms">+ xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.ktindex bd8b391f..0fdec6b6 100644--- a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt+++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt@@ -99,11 +99,12 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {if (!Settings.getActiveStatus(applicationContext)) {Timber.w("user is not active, stopping processing")- handleFailed(applicationContext, messageID, "MOBILE_APP_INACTIVE")+ handleFailed(applicationContext, messageID)return Result.failure()}val message = getMessage(applicationContext, messageID) ?: return Result.failure()+registerReceivers(applicationContext, message.id)sendMessage(@@ -126,10 +127,10 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {)}- private fun handleFailed(context: Context, messageID: String, reason: String) {+ private fun handleFailed(context: Context, messageID: String) {Timber.d("sending failed event for message with ID [${messageID}]")HttpSmsApiService(Settings.getApiKeyOrDefault(context))- .sendFailedEvent(messageID, ZonedDateTime.now(ZoneOffset.UTC), reason)+ .sendFailedEvent(messageID, ZonedDateTime.now(ZoneOffset.UTC), "MOBILE_APP_INACTIVE")}private fun getMessage(context: Context, messageID: String): Message? {diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.ktindex 9af21f0e..529747a6 100644--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt@@ -15,8 +15,8 @@ import java.util.logging.Logger.getLoggerclass HttpSmsApiService(private val apiKey: String) {private val apiKeyHeader = "x-api-key"- private val baseURL = URI("https://49b1-145-14-19-43.ngrok.io")- // private val baseURL = URI("https://api.httpsms.com")+ // private val baseURL = URI("https://49b1-145-14-19-43.ngrok.io")+ private val baseURL = URI("https://api.httpsms.com")private val jsonMediaType = "application/json; charset=utf-8".toMediaType()private val client = OkHttpClient()@@ -32,16 +32,17 @@ class HttpSmsApiService(private val apiKey: String) {val response = client.newCall(request).execute()if (response.isSuccessful) {- val payload = ResponseMessage.fromJson(response.body!!.string())?.data+ val payload = ResponseMessage.fromJson(response.body!!.string())?.dataif (payload == null) {Timber.e("cannot decode payload [${response.body}]")return null}+ Timber.w("response code [${response.code}]")response.close()return payload}- Timber.e("invalid response with code [${response.code}] and payload [${response.body}]")+ Timber.e("invalid response with code [${response.code}]")response.close()return null}diff --git a/android/build.gradle b/android/build.gradleindex 10e585d1..40f09798 100644--- a/android/build.gradle+++ b/android/build.gradle@@ -12,8 +12,8 @@ buildscript {}plugins {- id 'com.android.application' version '7.2.2' apply false- id 'com.android.library' version '7.2.2' apply false+ id 'com.android.application' version '7.3.0' apply false+ id 'com.android.library' version '7.3.0' apply falseid 'org.jetbrains.kotlin.android' version '1.6.21' apply false}diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.propertiesindex 0e654663..e7474120 100644--- a/android/gradle/wrapper/gradle-wrapper.properties+++ b/android/gradle/wrapper/gradle-wrapper.properties@@ -1,6 +1,6 @@#Thu Jun 23 15:32:32 EEST 2022distributionBase=GRADLE_USER_HOME-distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip+distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zipdistributionPath=wrapper/distszipStorePath=wrapper/distszipStoreBase=GRADLE_USER_HOMEdiff --git a/api/pkg/entities/phone.go b/api/pkg/entities/phone.goindex 83648aaf..17cea698 100644--- a/api/pkg/entities/phone.go+++ b/api/pkg/entities/phone.go@@ -29,6 +29,14 @@ func (phone *Phone) MessageExpirationDuration() time.Duration {return time.Duration(phone.MessageExpirationSeconds) * time.Second}+// MessageExpirationSecondsSanitized returns the message expiration seconds with default of 1 hour+func (phone *Phone) MessageExpirationSecondsSanitized() uint {+ if phone.MessageExpirationSeconds == 0 {+ return 60 * 60 // 1 hour+ }+ return phone.MessageExpirationSeconds+}+// MaxSendAttemptsSanitized returns the max send attempts replacing 0 with 1func (phone *Phone) MaxSendAttemptsSanitized() uint {if phone.MaxSendAttempts == 0 {diff --git a/api/pkg/handlers/message_handler.go b/api/pkg/handlers/message_handler.goindex c2392cf6..d997b281 100644--- a/api/pkg/handlers/message_handler.go+++ b/api/pkg/handlers/message_handler.go@@ -128,12 +128,19 @@ func (h *MessageHandler) GetOutstanding(c *fiber.Ctx) error {}message, err := h.service.GetOutstanding(ctx, request.ToGetOutstandingParams(c.Path(), h.userIDFomContext(c), timestamp))+ if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {+ msg := fmt.Sprintf("outstanding message with id [%s] already fetched", request.MessageID)+ ctxLogger.Warn(stacktrace.Propagate(err, msg))+ return h.responseNotFound(c, "outstanding message already processed")+ }+if err != nil {- msg := fmt.Sprintf("cannot get outstnading messgage with ID [%s]", request.MessageID)+ msg := fmt.Sprintf("cannot get outstanding messgage with ID [%s]", request.MessageID)ctxLogger.Error(stacktrace.Propagate(err, msg))return h.responseInternalServerError(c)}+ ctxLogger.Warn(stacktrace.NewError(fmt.Sprintf("New Message [%s]", spew.Sdump(message))))return h.responseOK(c, "outstanding message fetched successfully", message)}diff --git a/api/pkg/handlers/phone_handler.go b/api/pkg/handlers/phone_handler.goindex ab24d926..be741682 100644--- a/api/pkg/handlers/phone_handler.go+++ b/api/pkg/handlers/phone_handler.go@@ -119,7 +119,7 @@ func (h *PhoneHandler) Upsert(c *fiber.Ctx) error {if errors := h.validator.ValidateUpsert(ctx, request.Sanitize()); len(errors) != 0 {msg := fmt.Sprintf("validation errors [%s], while fetching phones [%+#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 phones")}phone, err := h.service.Upsert(ctx, request.ToUpsertParams(h.userFromContext(c), c.OriginalURL()))diff --git a/api/pkg/repositories/gorm_message_repository.go b/api/pkg/repositories/gorm_message_repository.goindex a4171842..e499a69c 100644--- a/api/pkg/repositories/gorm_message_repository.go+++ b/api/pkg/repositories/gorm_message_repository.go@@ -121,10 +121,20 @@ func (repository *gormMessageRepository) GetOutstanding(ctx context.Context, useUpdate("status", entities.MessageStatusSending).Error},)+ if errors.Is(err, gorm.ErrRecordNotFound) {+ msg := fmt.Sprintf("outstanding message with ID [%s] and userID [%s] does not exist", messageID, userID)+ return nil, repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, ErrCodeNotFound, msg))+ }+if err != nil {msg := fmt.Sprintf("cannot fetch outstanding message with userID [%s] and messageID [%s]", userID, messageID)return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))}+ if message == nil || message.ID == uuid.Nil {+ msg := fmt.Sprintf("outstanding message with ID [%s] and userID [%s] does not exist", messageID, userID)+ return nil, repository.tracer.WrapErrorSpan(span, stacktrace.NewErrorWithCode(ErrCodeNotFound, msg))+ }+return message, nil}diff --git a/api/pkg/requests/phone_update_request.go b/api/pkg/requests/phone_update_request.goindex 6fb3cda4..6d485540 100644--- a/api/pkg/requests/phone_update_request.go+++ b/api/pkg/requests/phone_update_request.go@@ -19,6 +19,9 @@ type PhoneUpsert struct {// MessageExpirationSeconds is the duration in seconds after sending a message when it is considered to be expired.MessageExpirationSeconds uint `json:"message_expiration_seconds" example:"12345"`+ // MaxSendAttempts is the number of attempts when sending an SMS message to handle the case where the phone is offline.+ MaxSendAttempts uint `json:"max_send_attempts" example:"2"`+FcmToken string `json:"fcm_token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....."`}@@ -52,11 +55,17 @@ func (input *PhoneUpsert) ToUpsertParams(user entities.AuthUser, source string)timeout = &duration}+ var maxSendAttempts *uint+ if input.MaxSendAttempts != 0 {+ maxSendAttempts = &input.MaxSendAttempts+ }+return services.PhoneUpsertParams{Source: source,PhoneNumber: *phone,MessagesPerMinute: messagesPerMinute,MessageExpirationDuration: timeout,+ MaxSendAttempts: maxSendAttempts,FcmToken: fcmToken,UserID: user.ID,}diff --git a/api/pkg/services/message_service.go b/api/pkg/services/message_service.goindex 26ea032e..8b0b056d 100644--- a/api/pkg/services/message_service.go+++ b/api/pkg/services/message_service.go@@ -64,7 +64,7 @@ func (service *MessageService) GetOutstanding(ctx context.Context, params Messagmessage, err := service.repository.GetOutstanding(ctx, params.UserID, params.MessageID)if err != nil {msg := fmt.Sprintf("could not fetch outstanding messages with params [%s]", spew.Sdump(params))- return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))}event, err := service.createMessagePhoneSendingEvent(params.Source, events.MessagePhoneSendingPayload{@@ -727,7 +727,7 @@ func (service *MessageService) CheckExpired(ctx context.Context, params MessageCreturn service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))}- if !message.IsPending() && !message.IsSending() {+ if !message.IsPending() && !message.IsSending() && !message.IsScheduled() {ctxLogger.Info(fmt.Sprintf("message with ID [%s] has status [%s] and is not expired", message.ID, message.Status))return nil}diff --git a/api/pkg/services/phone_notification_service.go b/api/pkg/services/phone_notification_service.goindex 4c573d68..82beb37b 100644--- a/api/pkg/services/phone_notification_service.go+++ b/api/pkg/services/phone_notification_service.go@@ -73,10 +73,14 @@ func (service *PhoneNotificationService) Send(ctx context.Context, params *Phonereturn 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{+ TTL: &ttl,+ },Token: *phone.FcmToken,})if err != nil {diff --git a/api/pkg/services/phone_service.go b/api/pkg/services/phone_service.goindex 4a3f8897..5b3e0dc9 100644--- a/api/pkg/services/phone_service.go+++ b/api/pkg/services/phone_service.go@@ -72,6 +72,7 @@ type PhoneUpsertParams struct {PhoneNumber phonenumbers.PhoneNumberFcmToken *stringMessagesPerMinute *uint+ MaxSendAttempts *uintMessageExpirationDuration *time.DurationSource stringUserID entities.UserID@@ -166,8 +167,8 @@ func (service *PhoneService) createPhone(ctx context.Context, params PhoneUpsertID: uuid.New(),UserID: params.UserID,FcmToken: params.FcmToken,- MessagesPerMinute: 0,- MessageExpirationSeconds: 0,+ MessagesPerMinute: 60,+ MessageExpirationSeconds: 60 * 60, // 1 hourMaxSendAttempts: 1,PhoneNumber: phonenumbers.Format(¶ms.PhoneNumber, phonenumbers.E164),CreatedAt: time.Now().UTC(),@@ -198,6 +199,10 @@ func (service *PhoneService) update(phone *entities.Phone, params PhoneUpsertParphone.MessagesPerMinute = *params.MessagesPerMinute}+ if params.MaxSendAttempts != nil && *params.MaxSendAttempts > 0 {+ phone.MaxSendAttempts = *params.MaxSendAttempts+ }+if params.MessageExpirationDuration != nil {phone.MessageExpirationSeconds = uint(params.MessageExpirationDuration.Seconds())}diff --git a/api/pkg/validators/phone_handler_validator.go b/api/pkg/validators/phone_handler_validator.goindex bcc8cf8c..fa3385ad 100644--- a/api/pkg/validators/phone_handler_validator.go+++ b/api/pkg/validators/phone_handler_validator.go@@ -69,10 +69,27 @@ func (validator *PhoneHandlerValidator) ValidateUpsert(_ context.Context, reques"min:0","max:60",},+ "max_send_attempts": []string{+ "min:0",+ "max:5",+ },+ "message_expiration_seconds": []string{+ "min:60",+ "max:3600",+ },},})- return v.ValidateStruct()+ result := v.ValidateStruct()+ if len(result) > 0 {+ return result+ }++ if request.MaxSendAttempts > 0 && request.MessageExpirationSeconds == 0 {+ result.Add("message_expiration_seconds", "message_expiration_seconds cannot be 0 when max_send_attempts is greater than 0")+ }++ return result}// ValidateDelete ValidateUpsert validates requests.PhoneDeletediff --git a/web/models/phone.ts b/web/models/phone.tsindex 0b74447f..3740634b 100644--- a/web/models/phone.ts+++ b/web/models/phone.ts@@ -5,6 +5,7 @@ export interface Phone {phone_number: stringcreated_at: stringupdated_at: string+ max_send_attempts: numbermessage_expiration_seconds: numbermessages_per_minute: number}diff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vueindex fca7020e..14163d92 100644--- a/web/pages/settings/index.vue+++ b/web/pages/settings/index.vue@@ -83,6 +83,9 @@<th v-if="$vuetify.breakpoint.lgAndUp" class="text-center">Fcm Token</th>+ <th v-if="$vuetify.breakpoint.lgAndUp" class="text-center">+ Retries+ </th><th class="text-center">Rate</th><th class="text-center">Updated At</th><th class="text-center">Action</th>@@ -104,6 +107,13 @@></v-checkbox></div></td>+ <td v-if="$vuetify.breakpoint.lgAndUp">+ <div class="d-flex justify-center">+ {{+ phone.max_send_attempts ? phone.max_send_attempts : 1+ }}+ </div>+ </td><td class="text-center"><span v-if="phone.messages_per_minute">{{ phone.messages_per_minute }}/min</span@@ -181,6 +191,15 @@label="Messages Per Minute"></v-text-field>+ <v-text-field+ v-model="activePhone.max_send_attempts"+ outlined+ type="number"+ dense+ placeholder="How many retries when sending an SMS"+ label="Max Send Attempts"+ >+ </v-text-field></v-col></v-row></v-container>@@ -252,6 +271,7 @@ export default Vue.extend({},},mounted() {+ this.$store.dispatch('clearAxiosError')if (!this.$store.getters.getAuthUser) {this.$store.dispatch('setNextRoute', this.$route.path)this.$router.push({ name: 'index' })@@ -272,12 +292,15 @@ export default Vue.extend({this.showPhoneEdit = true},- updatePhone() {+ async updatePhone() {this.updatingPhone = true+ await this.$store.dispatch('clearAxiosError')this.$store.dispatch('updatePhone', this.activePhone).finally(() => {- this.updatingPhone = false- this.showPhoneEdit = false- this.activePhone = null+ if (!this.$store.getters.getAxiosError) {+ this.updatingPhone = false+ this.showPhoneEdit = false+ this.activePhone = null+ }})},diff --git a/web/pages/threads/_id.vue b/web/pages/threads/_id.vueindex ca8558db..408a58ca 100644--- a/web/pages/threads/_id.vue+++ b/web/pages/threads/_id.vue@@ -97,7 +97,7 @@<v-list-item-group v-model="selectedMenuItem"><v-list-item @click.prevent="resendMessage(message)"><v-list-item-icon class="pl-2">- <v-icon dense>{{ mdiReferesh }}</v-icon>+ <v-icon dense>{{ mdiRefresh }}</v-icon></v-list-item-icon><v-list-item-content class="ml-n3"><v-list-item-title class="pr-16 py-1">@@ -140,9 +140,7 @@:size="14":width="1"class="mt-n2"- :color="- message.status === 'pending' ? 'primary' : 'warning'- "+ :color="statusColor(message)"></v-progress-circular><v-iconv-else-if="message.status === 'delivered'"@@ -302,7 +300,19 @@ export default Vue.extend({methods: {isPending(message: Message): boolean {- return ['sending', 'pending'].includes(message.status)+ return ['sending', 'pending', 'scheduled'].includes(message.status)+ },++ statusColor(message: Message): string {+ if (message.status === 'sending') {+ return 'warning'+ }++ if (message.status === 'scheduled') {+ return 'teal'+ }++ return 'primary'},canResend(message: Message): boolean {diff --git a/web/store/index.ts b/web/store/index.tsindex 1ae8b7bb..8013d77f 100644--- a/web/store/index.ts+++ b/web/store/index.ts@@ -1,4 +1,5 @@import { ActionContext } from 'vuex'+import { AxiosError, AxiosResponse } from 'axios'import { MessageThread } from '~/models/message-thread'import { Message } from '~/models/message'import { Heartbeat } from '~/models/heartbeat'@@ -28,6 +29,7 @@ export type AuthUser = {export type State = {owner: string | null+ axiosError: AxiosError | nullnextRoute: string | nullloadingThreads: booleanloadingMessages: boolean@@ -48,6 +50,7 @@ export const state = (): State => ({threadId: null,heartbeat: null,nextRoute: null,+ axiosError: null,loadingThreads: true,archivedThreads: false,loadingMessages: true,@@ -102,6 +105,10 @@ export const getters = {return state.authUser},+ getAxiosError(state: State): AxiosError | null {+ return state.axiosError+ },+isLocal(): boolean {return process.env.APP_ENV === 'local'},@@ -192,6 +199,9 @@ export const mutations = {setAuthUser(state: State, payload: AuthUser | null) {state.authUser = payload},+ setAxiosError(state: State, payload: AxiosError | null) {+ state.axiosError = payload+ },setNotification(state: State, notification: NotificationRequest) {state.notification = {...state.notification,@@ -300,17 +310,44 @@ export const actions = {},async updatePhone(context: ActionContext<State, State>, phone: Phone) {- await axios.put(`/v1/phones`, {- fcm_token: phone.fcm_token,- phone_number: phone.phone_number,- message_expiration_seconds: parseInt(- phone.message_expiration_seconds.toString()- ),- messages_per_minute: parseInt(phone.messages_per_minute.toString()),- })+ await axios+ .put(`/v1/phones`, {+ fcm_token: phone.fcm_token,+ phone_number: phone.phone_number,+ message_expiration_seconds: parseInt(+ phone.message_expiration_seconds.toString()+ ),+ max_send_attempts: parseInt(phone.max_send_attempts.toString()),+ messages_per_minute: parseInt(phone.messages_per_minute.toString()),+ })+ .catch((error: AxiosError) => {+ context.dispatch('handleAxiosError', error)+ })+ .then((response: any) => {+ context.dispatch('addNotification', {+ message: response.data.message,+ type: 'success',+ })+ })+await context.dispatch('loadPhones', true)},+ async handleAxiosError(+ context: ActionContext<State, State>,+ error: AxiosError+ ) {+ const errorMessage =+ error.response?.data?.data[Object.keys(error.response?.data?.data)[0]][0]+ await context.dispatch('addNotification', {+ message:+ (errorMessage ? errorMessage.replaceAll('_', ' ') : null) ??+ error.response?.data.message,+ type: 'error',+ })+ await context.commit('setAxiosError', error)+ },+async getHeartbeat(context: ActionContext<State, State>) {const response = await axios.get('/v1/heartbeats', {params: {@@ -402,6 +439,10 @@ export const actions = {}},+ async clearAxiosError(context: ActionContext<State, State>) {+ await context.commit('setAxiosError', null)+ },+async setOwner(context: ActionContext<State, State>, owner: string) {await context.commit('setOwner', owner)