Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
Making the server URL configurable #23
Acho Arnolda22f3528d28f
diff --git a/android/app/src/main/java/com/httpsms/DeliveredReceiver.kt b/android/app/src/main/java/com/httpsms/DeliveredReceiver.ktindex eb2f9d4b..b9d10be4 100644--- a/android/app/src/main/java/com/httpsms/DeliveredReceiver.kt+++ b/android/app/src/main/java/com/httpsms/DeliveredReceiver.kt@@ -24,7 +24,7 @@ internal class DeliveredReceiver : BroadcastReceiver() {}Thread {Timber.i("delivered message with ID [${messageId}]")- HttpSmsApiService(Settings.getApiKeyOrDefault(context)).sendDeliveredEvent(messageId!!, timestamp)+ HttpSmsApiService.create(context).sendDeliveredEvent(messageId!!, timestamp)}.start()}@@ -36,7 +36,7 @@ internal class DeliveredReceiver : BroadcastReceiver() {Thread {Timber.i("message with ID [${messageId}] not delivered")- HttpSmsApiService(Settings.getApiKeyOrDefault(context)).sendFailedEvent(messageId!!,timestamp, "NOT_DELIVERED")+ HttpSmsApiService.create(context).sendFailedEvent(messageId!!,timestamp, "NOT_DELIVERED")}.start()}}diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.ktindex 0fdec6b6..fe46bf20 100644--- a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt+++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt@@ -67,7 +67,7 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {if (Settings.isLoggedIn(this)) {Timber.d("updating phone with new fcm token")- HttpSmsApiService(Settings.getApiKeyOrDefault(this)).updatePhone(Settings.getOwnerOrDefault(this), token)+ HttpSmsApiService.create(this).updatePhone(Settings.getOwnerOrDefault(this), token)}}@@ -129,13 +129,13 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {private fun handleFailed(context: Context, messageID: String) {Timber.d("sending failed event for message with ID [${messageID}]")- HttpSmsApiService(Settings.getApiKeyOrDefault(context))+ HttpSmsApiService.create(context).sendFailedEvent(messageID, ZonedDateTime.now(ZoneOffset.UTC), "MOBILE_APP_INACTIVE")}private fun getMessage(context: Context, messageID: String): Message? {Timber.d("fetching message with ID [${messageID}]")- val message = HttpSmsApiService(Settings.getApiKeyOrDefault(context)).getOutstandingMessage(messageID)+ val message = HttpSmsApiService.create(context).getOutstandingMessage(messageID)if (message != null) {Timber.d("fetched message with ID [${message.id}]")diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.ktindex ee2785f8..4499d4cf 100644--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt@@ -1,5 +1,6 @@package com.httpsms+import android.content.Contextimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientimport okhttp3.Request@@ -13,10 +14,8 @@ import java.util.logging.Levelimport java.util.logging.Logger.getLogger-class HttpSmsApiService(private val apiKey: String) {+class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {private val apiKeyHeader = "x-api-key"- //private val baseURL = URI("https://a276-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.Builder().retryOnConnectionFailure(true).build()@@ -24,6 +23,15 @@ class HttpSmsApiService(private val apiKey: String) {getLogger(OkHttpClient::class.java.name).level = Level.FINE}+ companion object {+ fun create(context: Context): HttpSmsApiService {+ return HttpSmsApiService(+ Settings.getApiKeyOrDefault(context),+ Settings.getServerUrlOrDefault(context)+ )+ }+ }+fun getOutstandingMessage(messageID: String): Message? {val request: Request = Request.Builder().url(baseURL.resolve("/v1/messages/outstanding?message_id=${messageID}").toURL())@@ -174,21 +182,25 @@ class HttpSmsApiService(private val apiKey: String) {}- fun validateApiKey(): String? {+ fun validateApiKey(): Pair<String?, String?> {val request: Request = Request.Builder().url(baseURL.resolve("/v1/users/me").toURL()).header(apiKeyHeader, apiKey).get().build()- val response = client.newCall(request).execute()- if (!response.isSuccessful) {- Timber.e("error response [${response.body?.string()}] with code [${response.code}] while verifying apiKey [$apiKey]")- return "Cannot validate the API key. Check if it is correct and try again."- }+ try {+ val response = client.newCall(request).execute()+ if (!response.isSuccessful) {+ Timber.e("error response [${response.body?.string()}] with code [${response.code}] while verifying apiKey [$apiKey]")+ return Pair("Cannot validate the API key. Check if it is correct and try again.", null);+ }- response.close()- Timber.i("api key [$apiKey] is valid" )- return null+ response.close()+ Timber.i("api key [$apiKey] and server url [$baseURL] are valid" )+ return Pair(null, null)+ } catch (ex: Exception) {+ return Pair(null, ex.message)+ }}}diff --git a/android/app/src/main/java/com/httpsms/LoginActivity.kt b/android/app/src/main/java/com/httpsms/LoginActivity.ktindex 352d477d..e57352a6 100644--- a/android/app/src/main/java/com/httpsms/LoginActivity.kt+++ b/android/app/src/main/java/com/httpsms/LoginActivity.kt@@ -9,6 +9,7 @@ import android.os.Bundleimport android.telephony.PhoneNumberUtilsimport android.telephony.TelephonyManagerimport android.view.View+import android.webkit.URLUtilimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.ActivityCompatimport androidx.lifecycle.MutableLiveData@@ -17,6 +18,7 @@ import com.google.android.material.progressindicator.LinearProgressIndicatorimport com.google.android.material.textfield.TextInputEditTextimport com.google.android.material.textfield.TextInputLayoutimport timber.log.Timber+import java.net.URIclass LoginActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {@@ -25,6 +27,7 @@ class LoginActivity : AppCompatActivity() {setContentView(R.layout.activity_login)registerListeners()setPhoneNumber()+ setServerURL()}private fun registerListeners() {@@ -43,6 +46,12 @@ class LoginActivity : AppCompatActivity() {Timber.d("phone number [$phoneNumber] set successfully")}+ private fun setServerURL() {+ val serverUrlInput = findViewById<TextInputEditText>(R.id.loginServerUrlInput)+ serverUrlInput.setText(getString(R.string.default_server_url))+ Timber.d("default server url [${serverUrlInput.text.toString()}] set successfully")+ }+@SuppressLint("HardwareIds")private fun getPhoneNumber(context: Context): String? {val telephonyManager = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager@@ -81,6 +90,12 @@ class LoginActivity : AppCompatActivity() {val apiKey = findViewById<TextInputEditText>(R.id.loginApiKeyTextInput)apiKey.isEnabled = false+ val serverUrlLayout = findViewById<TextInputLayout>(R.id.loginServerUrlLayout)+ serverUrlLayout.error = null++ val serverUrl = findViewById<TextInputEditText>(R.id.loginServerUrlInput)+ serverUrl.isEnabled = false+val phoneNumberLayout = findViewById<TextInputLayout>(R.id.loginPhoneNumberLayout)phoneNumberLayout.error = null@@ -89,6 +104,7 @@ class LoginActivity : AppCompatActivity() {val resetView = fun () {apiKey.isEnabled = true+ serverUrl.isEnabled = trueprogressBar.visibility = View.INVISIBLEphoneNumber.isEnabled = trueloginButton().isEnabled = true@@ -104,17 +120,38 @@ class LoginActivity : AppCompatActivity() {return}- val liveData = MutableLiveData<String?>()+ if(!URLUtil.isValidUrl(serverUrl.text.toString().trim())) {+ Timber.e("url number [${serverUrl.text.toString()}] is not a valid URL")+ resetView()+ serverUrlLayout.error = "Server URL [${serverUrl.text.toString()}] is invalid"+ return+ }++ if (!URLUtil.isHttpsUrl(serverUrl.text.toString().trim())) {+ Timber.e("url number [${serverUrl.text.toString()}] is not an https URL")+ resetView()+ serverUrlLayout.error = "Server URL [${serverUrl.text.toString()}] must be HTTPS"+ return+ }++ val liveData = MutableLiveData<Pair<String?, String?>>()liveData.observe(this) { authResult ->run {progressBar.visibility = View.INVISIBLE- if (authResult != null) {+ if (authResult.first != null) {+ resetView()+ apiKeyLayout.error = authResult.first+ return@run+ }++ if (authResult.second != null) {resetView()- apiKeyLayout.error = authResult+ serverUrlLayout.error = authResult.secondreturn@run}Settings.setApiKeyAsync(this, apiKey.text.toString())+ Settings.setServerUrlAsync(this, serverUrl.text.toString().trim())val e164PhoneNumber = PhoneNumberUtils.formatNumberToE164(phoneNumber.text.toString(),@@ -128,9 +165,9 @@ class LoginActivity : AppCompatActivity() {}Thread {- val error = HttpSmsApiService(apiKey.text.toString()).validateApiKey()+ val error = HttpSmsApiService(apiKey.text.toString(), URI(serverUrl.text.toString().trim())).validateApiKey()liveData.postValue(error)- Timber.i("login successful")+ Timber.d("finished validating api URL")}.start()}diff --git a/android/app/src/main/java/com/httpsms/MainActivity.kt b/android/app/src/main/java/com/httpsms/MainActivity.ktindex 75033682..f3edcbc3 100644--- a/android/app/src/main/java/com/httpsms/MainActivity.kt+++ b/android/app/src/main/java/com/httpsms/MainActivity.kt@@ -140,8 +140,7 @@ class MainActivity : AppCompatActivity() {}Thread {- val updated = HttpSmsApiService(Settings.getApiKeyOrDefault(context))- .updatePhone(Settings.getOwnerOrDefault(context), Settings.getFcmToken(context) ?: "")+ val updated = HttpSmsApiService.create(context).updatePhone(Settings.getOwnerOrDefault(context), Settings.getFcmToken(context) ?: "")if (updated) {Settings.setFcmTokenLastUpdateTimestampAsync(context, currentTimeStamp)Timber.i("fcm token uploaded successfully")@@ -329,7 +328,7 @@ class MainActivity : AppCompatActivity() {Thread {var error: String? = nulltry {- HttpSmsApiService(Settings.getApiKeyOrDefault(context)).storeHeartbeat(Settings.getOwnerOrDefault(context))+ HttpSmsApiService.create(context).storeHeartbeat(Settings.getOwnerOrDefault(context))Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())} catch (exception: Exception) {Timber.e(exception)diff --git a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt b/android/app/src/main/java/com/httpsms/ReceivedReceiver.ktindex 6623ebb6..11a7ec81 100644--- a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt+++ b/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt@@ -47,7 +47,7 @@ class ReceivedReceiver: BroadcastReceiver()Thread {Timber.i("forwarding received message from [${from}]")- HttpSmsApiService(Settings.getApiKeyOrDefault(context)).receive(from, to, content, timestamp)+ HttpSmsApiService.create(context).receive(from, to, content, timestamp)}.start()}}diff --git a/android/app/src/main/java/com/httpsms/SentReceiver.kt b/android/app/src/main/java/com/httpsms/SentReceiver.ktindex 6c251277..3b67d070 100644--- a/android/app/src/main/java/com/httpsms/SentReceiver.kt+++ b/android/app/src/main/java/com/httpsms/SentReceiver.kt@@ -29,7 +29,7 @@ internal class SentReceiver : BroadcastReceiver() {Thread {Timber.d("sent message with ID [${messageId}]")- HttpSmsApiService(Settings.getApiKeyOrDefault(context)).sendSentEvent(messageId!!,timestamp)+ HttpSmsApiService.create(context).sendSentEvent(messageId!!,timestamp)}.start()}@@ -41,7 +41,7 @@ internal class SentReceiver : BroadcastReceiver() {Thread {Timber.i("message with ID [${messageId}] not sent with reason [$reason]")- HttpSmsApiService(Settings.getApiKeyOrDefault(context)).sendFailedEvent(messageId!!, timestamp, reason)+ HttpSmsApiService.create(context).sendFailedEvent(messageId!!, timestamp, reason)}.start()}}diff --git a/android/app/src/main/java/com/httpsms/Settings.kt b/android/app/src/main/java/com/httpsms/Settings.ktindex a00beccc..a9fcc1fe 100644--- a/android/app/src/main/java/com/httpsms/Settings.kt+++ b/android/app/src/main/java/com/httpsms/Settings.kt@@ -3,6 +3,7 @@ package com.httpsmsimport android.content.Contextimport androidx.preference.PreferenceManagerimport timber.log.Timber+import java.net.URIobject Settings {private const val DEFAULT_PHONE_NUMBER = "66836863" // NOT_FOUND :)@@ -10,6 +11,7 @@ object Settings {private const val SETTINGS_OWNER = "SETTINGS_OWNER"private const val SETTINGS_ACTIVE = "SETTINGS_ACTIVE_STATUS"private const val SETTINGS_API_KEY = "SETTINGS_API_KEY"+ private const val SETTINGS_SERVER_URL = "SETTINGS_SERVER_URL"private const val SETTINGS_FCM_TOKEN = "SETTINGS_FCM_TOKEN"private const val SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP = "SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP"private const val SETTINGS_HEARTBEAT_TIMESTAMP = "SETTINGS_HEARTBEAT_TIMESTAMP"@@ -108,6 +110,31 @@ object Settings {return getApiKey(context) ?: ""}+ fun getServerUrlOrDefault(context:Context): URI {+ val urlString = getServerUrl(context) ?: "https://api.httpsms.com"+ return URI(urlString)+ }++ private fun getServerUrl(context: Context): String? {+ Timber.d(Settings::getServerUrl.name)++ val serverUrl = PreferenceManager+ .getDefaultSharedPreferences(context)+ .getString(this.SETTINGS_SERVER_URL,null)++ Timber.d("SETTINGS_SERVER_URL: [$serverUrl]")+ return serverUrl+ }++ fun setServerUrlAsync(context: Context, serverURL: String?) {+ Timber.d(Settings::SETTINGS_SERVER_URL.name)++ PreferenceManager.getDefaultSharedPreferences(context)+ .edit()+ .putString(this.SETTINGS_SERVER_URL, serverURL)+ .apply()+ }+fun setApiKeyAsync(context: Context, apiKey: String?) {Timber.d(Settings::setApiKeyAsync.name)diff --git a/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt b/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.ktindex bf6666cc..3edd2d6f 100644--- a/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt+++ b/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt@@ -20,7 +20,7 @@ class HeartbeatWorker(appContext: Context, workerParams: WorkerParameters) : Worreturn Result.failure()}- HttpSmsApiService(Settings.getApiKeyOrDefault(applicationContext))+ HttpSmsApiService.create(applicationContext).storeHeartbeat(Settings.getOwnerOrDefault(applicationContext))Timber.d("finished sending heartbeat to server")@@ -33,4 +33,4 @@ class HeartbeatWorker(appContext: Context, workerParams: WorkerParameters) : Wor-}+}diff --git a/android/app/src/main/res/layout/activity_login.xml b/android/app/src/main/res/layout/activity_login.xmlindex 86695071..bffec183 100644--- a/android/app/src/main/res/layout/activity_login.xml+++ b/android/app/src/main/res/layout/activity_login.xml@@ -35,6 +35,26 @@app:layout_constraintHorizontal_bias="0.498"app:layout_constraintStart_toStartOf="parent" />+ <com.google.android.material.textfield.TextInputLayout+ android:id="@+id/loginApiKeyTextInputLayout"+ style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ app:errorEnabled="true"+ android:hint="@string/text_area_api_key"+ app:layout_constraintBottom_toBottomOf="parent"+ app:layout_constraintTop_toTopOf="parent"+ tools:layout_editor_absoluteX="16dp">++ <com.google.android.material.textfield.TextInputEditText+ android:id="@+id/loginApiKeyTextInput"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:inputType="textMultiLine"+ tools:ignore="TextContrastCheck" />++ </com.google.android.material.textfield.TextInputLayout>+<com.google.android.material.textfield.TextInputLayoutandroid:id="@+id/loginPhoneNumberLayout"style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"@@ -58,19 +78,23 @@</com.google.android.material.textfield.TextInputLayout>+<com.google.android.material.textfield.TextInputLayout- android:id="@+id/loginApiKeyTextInputLayout"+ android:id="@+id/loginServerUrlLayout"style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"android:layout_width="match_parent"android:layout_height="wrap_content"+ android:layout_marginTop="-24dp"+ android:hint="@string/server_url"app:errorEnabled="true"- android:hint="@string/text_area_api_key"+ app:placeholderText="@string/login_server_url_hint"app:layout_constraintBottom_toBottomOf="parent"- app:layout_constraintTop_toTopOf="parent"+ app:layout_constraintTop_toBottomOf="@+id/loginPhoneNumberLayout"+ app:layout_constraintVertical_bias="0.137"tools:layout_editor_absoluteX="16dp"><com.google.android.material.textfield.TextInputEditText- android:id="@+id/loginApiKeyTextInput"+ android:id="@+id/loginServerUrlInput"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textMultiLine"@@ -86,7 +110,7 @@android:orientation="vertical"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"- app:layout_constraintTop_toBottomOf="@+id/loginPhoneNumberLayout">+ app:layout_constraintTop_toBottomOf="@+id/loginServerUrlLayout"><com.google.android.material.button.MaterialButtonandroid:id="@+id/loginButton"diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 2500e6c9..b10d0c24 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -10,6 +10,9 @@<string name="get_your_api_key">Open\nhttpsms.com/settings\nto get your API key</string><string name="main_log_out">Log Out</string><string name="login_phone_number_hint">International phone number in E.164 format</string>+ <string name="login_server_url_hint">e.g https://api.httpsms.com</string><string name="phone_number">Phone Number</string><string name="send_heartbeat">Send Heartbeat</string>+ <string name="server_url">Server URL</string>+ <string name="default_server_url">https://api.httpsms.com</string></resources>diff --git a/api/pkg/handlers/message_handler.go b/api/pkg/handlers/message_handler.goindex 34de05f3..a66a0ef0 100644--- a/api/pkg/handlers/message_handler.go+++ b/api/pkg/handlers/message_handler.go@@ -2,6 +2,7 @@ package handlersimport ("fmt"+ "sort""time""github.com/NdoleStudio/httpsms/pkg/repositories"@@ -67,6 +68,8 @@ func (h *MessageHandler) PostSend(c *fiber.Ctx) error {ctx, span := h.tracer.StartFromFiberCtx(c)defer span.End()+ sort.Search()+ctxLogger := h.tracer.CtxLogger(h.logger, span)var request requests.MessageSend