Skip to content

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

Fix bug with country code

Acho Arnold2cabe5d7b32e
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 8eb2bee2..e6b02d56 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -51,7 +51,7 @@ android {
}
dependencies {
- implementation platform('com.google.firebase:firebase-bom:33.5.1')
+ implementation platform('com.google.firebase:firebase-bom:33.13.0')
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-messaging-ktx'
@@ -66,6 +66,7 @@ dependencies {
implementation 'org.apache.commons:commons-text:1.12.0'
implementation 'com.google.android.material:material:1.12.0'
implementation 'androidx.constraintlayout:constraintlayout:2.2.0'
+ implementation 'com.googlecode.libphonenumber:libphonenumber:9.0.4'
implementation 'androidx.core:core-ktx:1.15.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
index 3389b186..3d813e13 100644
--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
@@ -217,7 +217,11 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
if (!response.isSuccessful) {
Timber.e("error response [${response.body?.string()}] with code [${response.code}] while updating FCM token [$fcmToken] with apiKey [$apiKey]")
response.close()
- return Triple(null,"Cannot validate the API key. Check if it is correct and try again.", null)
+ if (response.code == 401) {
+ Timber.e("invalid API key [$apiKey]")
+ return Triple(null, "Cannot validate the API key. Check if it is correct and try again.", null)
+ }
+ return Triple(null,null, "Cannot login to the server, Make sure the phone number is in international format e.g +18005550100")
}
Timber.i("FCM token submitted correctly with API key [$apiKey] and server url [$baseURL]" )
diff --git a/android/app/src/main/java/com/httpsms/LoginActivity.kt b/android/app/src/main/java/com/httpsms/LoginActivity.kt
index 9f4b1a9b..babe12df 100644
--- a/android/app/src/main/java/com/httpsms/LoginActivity.kt
+++ b/android/app/src/main/java/com/httpsms/LoginActivity.kt
@@ -7,7 +7,6 @@ import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
-import android.telephony.PhoneNumberUtils
import android.telephony.TelephonyManager
import android.view.View
import android.webkit.URLUtil
@@ -23,6 +22,7 @@ import com.google.android.material.button.MaterialButton
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
+import com.httpsms.validators.PhoneNumberValidator
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions
import timber.log.Timber
@@ -180,7 +180,7 @@ class LoginActivity : AppCompatActivity() {
Timber.d("login button clicked")
val error = isGooglePlayServicesAvailable()
- if (error != null || Settings.getFcmToken(this) == null) {
+ if (error != null) {
Timber.d("google play services not installed [${error}]")
Toast.makeText(this, error, Toast.LENGTH_SHORT).show()
return
@@ -188,7 +188,7 @@ class LoginActivity : AppCompatActivity() {
if (Settings.getFcmToken(this) == null) {
Timber.d("The FCM token is not set")
- Toast.makeText(this, "Cannot find FCM token. Make sure you have google play services installed", Toast.LENGTH_LONG).show()
+ Toast.makeText(this, "Cannot find FCM token. Make sure you have Google Play Services installed", Toast.LENGTH_LONG).show()
return
}
@@ -220,6 +220,8 @@ class LoginActivity : AppCompatActivity() {
val phoneNumberSIM2 = findViewById<TextInputEditText>(R.id.loginPhoneNumberInputSIM2)
phoneNumberSIM2.isEnabled = false
+ val countryCode = getCountryCode()
+
val resetView = fun () {
apiKey.isEnabled = true
serverUrl.isEnabled = true
@@ -229,25 +231,17 @@ class LoginActivity : AppCompatActivity() {
loginButton().isEnabled = true
}
- if (
- !PhoneNumberUtils.isWellFormedSmsAddress(phoneNumber.text.toString().trim()) ||
- !PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber.text.toString().trim())
- ) {
+ if (!PhoneNumberValidator.isValidPhoneNumber(phoneNumber.text.toString().trim(), countryCode)) {
Timber.e("[SIM1] phone number [${phoneNumber.text.toString()}] is not valid")
resetView()
- phoneNumberLayout.error = "Invalid E.164 phone number"
+ phoneNumberLayout.error = "Enter an international phone number in the E.164 format"
return
}
- if (
- SmsManagerService.isDualSIM(this) && (
- !PhoneNumberUtils.isWellFormedSmsAddress(phoneNumberSIM2.text.toString().trim()) ||
- !PhoneNumberUtils.isGlobalPhoneNumber(phoneNumberSIM2.text.toString().trim())
- )
- ) {
+ if (SmsManagerService.isDualSIM(this) && !PhoneNumberValidator.isValidPhoneNumber(phoneNumberSIM2.text.toString().trim(), countryCode)) {
Timber.e("[SIM2] phone number [${phoneNumberSIM2.text.toString()}] is not valid")
resetView()
- phoneNumberLayoutSIM2.error = "Invalid E.164 phone number"
+ phoneNumberLayoutSIM2.error = "Enter an international phone number in the E.164 format"
return
}
@@ -284,11 +278,11 @@ class LoginActivity : AppCompatActivity() {
Settings.setApiKeyAsync(this, apiKey.text.toString())
Settings.setServerUrlAsync(this, serverUrl.text.toString().trim())
- val e164PhoneNumber = formatE164(phoneNumber.text.toString().trim())
+ val e164PhoneNumber = PhoneNumberValidator.formatE164(phoneNumber.text.toString().trim(), countryCode)
Settings.setSIM1PhoneNumber(this, e164PhoneNumber)
if(SmsManagerService.isDualSIM(this)) {
- val sim2PhoneNumber = formatE164(phoneNumberSIM2.text.toString().trim())
+ val sim2PhoneNumber = PhoneNumberValidator.formatE164(phoneNumberSIM2.text.toString().trim(), countryCode)
Settings.setSIM2PhoneNumber(this, sim2PhoneNumber)
}
@@ -300,7 +294,7 @@ class LoginActivity : AppCompatActivity() {
Thread {
val service = HttpSmsApiService(apiKey.text.toString(), URI(serverUrl.text.toString().trim()))
- var e164PhoneNumber = formatE164(phoneNumber.text.toString().trim())
+ var e164PhoneNumber = PhoneNumberValidator.formatE164(phoneNumber.text.toString().trim(), countryCode)
var response = service.updateFcmToken(e164PhoneNumber, Constants.SIM1, Settings.getFcmToken(this) ?: "")
if(response.second != null || response.third != null) {
Timber.e("error updating fcm token [${response.second}], third [${response.third}]")
@@ -314,7 +308,7 @@ class LoginActivity : AppCompatActivity() {
return@Thread
}
- e164PhoneNumber = formatE164(phoneNumberSIM2.text.toString().trim())
+ e164PhoneNumber = PhoneNumberValidator.formatE164(phoneNumberSIM2.text.toString().trim(), countryCode)
response = service.updateFcmToken(e164PhoneNumber, Constants.SIM2, Settings.getFcmToken(this) ?: "")
liveData.postValue(Pair(response.second, response.third))
@@ -322,33 +316,6 @@ class LoginActivity : AppCompatActivity() {
}.start()
}
- private fun formatE164(number: String): String {
- var phoneNumber = number.trim()
- if (!number.startsWith("+")) {
- phoneNumber = "+$number"
- }
-
- Timber.d("formatting phone number [${phoneNumber}] into e164")
-
- val formattedNumber = PhoneNumberUtils.formatNumberToE164(
- phoneNumber,
- this.resources.configuration.locales.get(0).country
- )
-
- if (formattedNumber !== null) {
- return formattedNumber
- }
-
- return phoneNumber;
- }
-
- private fun addPlus(number: String): String {
- if (number.startsWith("+")) {
- return number
- }
- return "+$number"
- }
-
private fun redirectToMain() {
if (!Settings.isLoggedIn(this)) {
return
@@ -362,4 +329,18 @@ class LoginActivity : AppCompatActivity() {
private fun loginButton(): MaterialButton {
return findViewById(R.id.loginButton)
}
+
+ private fun getCountryCode() : String {
+ // Get the TelephonyManager from the system services
+ val tm = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
+
+ // Get the network country ISO code and convert it to uppercase
+ val code = tm.networkCountryIso.uppercase()
+
+ // If the country code is empty, retrieve the country code from the device's locale
+ if (code.isEmpty()) {
+ return this.resources.configuration.locales.get(0).country.uppercase()
+ }
+ return code
+ }
}
diff --git a/android/app/src/main/java/com/httpsms/validators/PhoneNumberValidator.kt b/android/app/src/main/java/com/httpsms/validators/PhoneNumberValidator.kt
new file mode 100644
index 00000000..7e9d2c42
--- /dev/null
+++ b/android/app/src/main/java/com/httpsms/validators/PhoneNumberValidator.kt
@@ -0,0 +1,37 @@
+package com.httpsms.validators
+
+import com.google.i18n.phonenumbers.PhoneNumberUtil
+import timber.log.Timber
+
+class PhoneNumberValidator {
+ companion object {
+ private val phoneNumberUtil = PhoneNumberUtil.getInstance()
+ fun isValidPhoneNumber(phoneNumber: String, countryCode: String): Boolean {
+ Timber.e(countryCode)
+ return try {
+ if (phoneNumber.isEmpty()) {
+ return false
+ }
+ val number = phoneNumberUtil.parse(fixNumber(phoneNumber), countryCode)
+ phoneNumberUtil.isValidNumber(number)
+ } catch (e: Exception) {
+ false
+ }
+ }
+ fun formatE164(phoneNumber: String, countryCode: String): String {
+ return try {
+ val number = phoneNumberUtil.parse(fixNumber(phoneNumber), countryCode)
+ phoneNumberUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164)
+ } catch (e: Exception) {
+ phoneNumber
+ }
+ }
+
+ private fun fixNumber(phoneNumber: String): String {
+ if (phoneNumber.length >= 11 && !phoneNumber.startsWith("+")) {
+ return "+${phoneNumber}"
+ }
+ return phoneNumber
+ }
+ }
+}
diff --git a/android/build.gradle b/android/build.gradle
index 7c9757c6..37f2b2d0 100644
--- a/android/build.gradle
+++ b/android/build.gradle
@@ -1,7 +1,7 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
- kotlin_version = '1.9.10'
+ kotlin_version = '2.1.0'
}
repositories {
// Check that you have the following line (if not, add it):
diff --git a/api/pkg/validators/validator.go b/api/pkg/validators/validator.go
index 7ca86f61..bc7111e8 100644
--- a/api/pkg/validators/validator.go
+++ b/api/pkg/validators/validator.go
@@ -29,12 +29,12 @@ func init() {
govalidator.AddCustomRule(phoneNumberRule, func(field string, rule string, message string, value interface{}) error {
phoneNumber, ok := value.(string)
if !ok {
- return fmt.Errorf("The %s field must be a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field)
+ return fmt.Errorf("The %s field must be a valid E.164 phone number in the international format e.g +18005550100", field)
}
_, err := phonenumbers.Parse(phoneNumber, phonenumbers.UNKNOWN_REGION)
if err != nil {
- return fmt.Errorf("The %s field must be a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field)
+ return fmt.Errorf("The %s field must be a valid E.164 phone number in the international format e.g +18005550100", field)
}
return nil
@@ -49,7 +49,7 @@ func init() {
for index, number := range phoneNumbers {
_, err := phonenumbers.Parse(number, phonenumbers.UNKNOWN_REGION)
if err != nil {
- return fmt.Errorf("The %s field in index [%d] must be a valid E.164 phone number: https://en.wikipedia.org/wiki/E.164", field, index)
+ return fmt.Errorf("The %s field in index [%d] must be a valid E.164 phone number in the international format e.g +18005550100", field, index)
}
}