Skip to content

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

Add more support for dual sim phones

Acho Arnold2c195a1ceede
diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
index e7f58006..dcfa1182 100644
--- a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
+++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
@@ -123,13 +123,13 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
return Result.failure()
}
- if (!Settings.getActiveStatus(applicationContext)) {
- Timber.w("user is not active, stopping processing")
+ val message = getMessage(applicationContext, messageID) ?: return Result.failure()
+ if (!Settings.getActiveStatus(applicationContext, message.sim)) {
+ Timber.w("[${message.sim}] SIM is not active, stopping processing")
handleFailed(applicationContext, messageID)
return Result.failure()
}
- val message = getMessage(applicationContext, messageID) ?: return Result.failure()
val parts = getMessageParts(applicationContext, message)
if (parts.size == 1) {
return handleSingleMessage(applicationContext, message)
diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
index 1523b15e..db5166e0 100644
--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
@@ -69,7 +69,7 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
sendEvent(messageId, "FAILED", timestamp, reason)
}
- fun receive(from: String, to: String, content: String, timestamp: ZonedDateTime) {
+ fun receive(sim: String, from: String, to: String, content: String, timestamp: ZonedDateTime) {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'000000'ZZZZZ")
val timestampString = formatter.format(timestamp).replace("+", "Z")
@@ -77,6 +77,7 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
val body = """
{
"content": "${StringEscapeUtils.escapeJson(content)}",
+ "sim": "$sim",
"from": "$from",
"timestamp": "$timestampString",
"to": "$to"
diff --git a/android/app/src/main/java/com/httpsms/LoginActivity.kt b/android/app/src/main/java/com/httpsms/LoginActivity.kt
index e75ba99e..da097d1b 100644
--- a/android/app/src/main/java/com/httpsms/LoginActivity.kt
+++ b/android/app/src/main/java/com/httpsms/LoginActivity.kt
@@ -5,12 +5,14 @@ import android.annotation.SuppressLint
import android.content.Context
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
import android.widget.LinearLayout
+import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.MutableLiveData
@@ -32,6 +34,16 @@ class LoginActivity : AppCompatActivity() {
setServerURL()
}
+ override fun onStart() {
+ super.onStart()
+ Timber.i("on start")
+ requestPermissions()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ }
+
private fun registerListeners() {
loginButton().setOnClickListener { onLoginClick() }
}
@@ -39,8 +51,11 @@ class LoginActivity : AppCompatActivity() {
private fun disableSim2() {
if (SmsManagerService.isDualSIM(this)) {
Timber.d("dual sim detected")
+ val sim2Layout = findViewById<LinearLayout>(R.id.loginPhoneNumberLayoutSIM2)
+ sim2Layout.visibility = LinearLayout.VISIBLE
return
}
+ Timber.e("is dual sim ${SmsManagerService.isDualSIM(this)}")
val sim2Layout = findViewById<LinearLayout>(R.id.loginPhoneNumberLayoutSIM2)
sim2Layout.visibility = View.GONE
}
@@ -54,7 +69,7 @@ class LoginActivity : AppCompatActivity() {
val phoneInput = findViewById<TextInputEditText>(R.id.loginPhoneNumberInputSIM1)
phoneInput.setText(phoneNumber)
- Timber.d("phone number [$phoneNumber] set successfully")
+ Timber.d("[SIM1] phone number [$phoneNumber] set successfully")
}
private fun setServerURL() {
@@ -88,6 +103,31 @@ class LoginActivity : AppCompatActivity() {
return telephonyManager.line1Number
}
+ private fun requestPermissions() {
+ Timber.d("requesting permissions")
+ val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
+ permissions.entries.forEach {
+ Timber.d("${it.key} = ${it.value}")
+ }
+ }
+
+ var permissions = arrayOf(
+ Manifest.permission.SEND_SMS,
+ Manifest.permission.RECEIVE_SMS,
+ Manifest.permission.READ_PHONE_NUMBERS,
+ Manifest.permission.READ_SMS,
+ Manifest.permission.READ_PHONE_STATE
+ )
+
+ if(Build.VERSION.SDK_INT >= 33) {
+ permissions += Manifest.permission.POST_NOTIFICATIONS
+ }
+
+ requestPermissionLauncher.launch(permissions)
+
+ Timber.d("creating permissions launcher")
+ }
+
private fun onLoginClick() {
Timber.d("login button clicked")
@@ -132,7 +172,7 @@ class LoginActivity : AppCompatActivity() {
!PhoneNumberUtils.isWellFormedSmsAddress(phoneNumber.text.toString()) ||
!PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber.text.toString())
) {
- Timber.e("phone number [${phoneNumber.text.toString()}] is not valid")
+ Timber.e("[SIM1] phone number [${phoneNumber.text.toString()}] is not valid")
resetView()
phoneNumberLayout.error = "Invalid E.164 phone number"
return
@@ -144,7 +184,7 @@ class LoginActivity : AppCompatActivity() {
!PhoneNumberUtils.isGlobalPhoneNumber(phoneNumberSIM2.text.toString())
)
) {
- Timber.e("phone number [${phoneNumberSIM2.text.toString()}] is not valid")
+ Timber.e("[SIM2] phone number [${phoneNumberSIM2.text.toString()}] is not valid")
resetView()
phoneNumberLayoutSIM2.error = "Invalid E.164 phone number"
return
diff --git a/android/app/src/main/java/com/httpsms/MainActivity.kt b/android/app/src/main/java/com/httpsms/MainActivity.kt
index b7b01b44..097b0b24 100644
--- a/android/app/src/main/java/com/httpsms/MainActivity.kt
+++ b/android/app/src/main/java/com/httpsms/MainActivity.kt
@@ -27,6 +27,7 @@ import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.google.android.material.button.MaterialButton
+import com.google.android.material.card.MaterialCardView
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.switchmaterial.SwitchMaterial
import com.httpsms.services.StickyNotificationService
@@ -54,51 +55,79 @@ class MainActivity : AppCompatActivity() {
createChannel()
- requestPermissions(this)
-
- setOwner(getPhoneNumber(this))
+ setCardContent(this)
setActiveStatus(this)
registerListeners()
refreshToken(this)
startStickyNotification(this)
scheduleHeartbeatWorker(this)
- setLastHeartbeatTimestamp(this)
setVersion()
setHeartbeatListener(this)
setBatteryOptimizationListener()
}
+ override fun onStart() {
+ super.onStart()
+ requestPermissions(this)
+ }
+
override fun onResume() {
super.onResume()
Timber.d( "on activity resume")
redirectToLogin()
- setOwner(getPhoneNumber(this))
refreshToken(this)
- setLastHeartbeatTimestamp(this)
+ setCardContent(this)
setBatteryOptimizationListener()
}
- private fun setLastHeartbeatTimestamp(context: Context) {
- val refreshTimestampView = findViewById<TextView>(R.id.cardRefreshTime)
- val timestamp = Settings.getHeartbeatTimestamp(context)
+ private fun setVersion() {
+ val appVersionView = findViewById<TextView>(R.id.mainAppVersion)
+ appVersionView.text = format(getString(R.string.app_version), BuildConfig.VERSION_NAME)
+ }
- if (timestamp == 0.toLong()) {
- Timber.d("no heartbeat timestamp has been set")
- refreshTimestampView.text = "--"
+ private fun setCardContent(context: Context) {
+ val titleText = findViewById<TextView>(R.id.cardPhoneNumber)
+ titleText.text = PhoneNumberUtils.formatNumber(Settings.getSIM1PhoneNumber(this), Locale.getDefault().country)
+
+ val titleTextSIM2 = findViewById<TextView>(R.id.cardPhoneNumberSIM2)
+ titleTextSIM2.text = PhoneNumberUtils.formatNumber(Settings.getSIM2PhoneNumber(this), Locale.getDefault().country)
+
+ setLastHeartbeatTimestamp(context)
+
+ if(!Settings.isDualSIM(context)) {
+ val sim2Card = findViewById<MaterialCardView>(R.id.mainPhoneCardSIM2)
+ sim2Card.visibility = MaterialCardView.GONE
+ }
+ }
+
+ private fun requestPermissions(context:Context) {
+ if(!Settings.isLoggedIn(context)) {
return
}
- val timestampZdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC)
- val localTime = timestampZdt.withZoneSameInstant(ZoneId.systemDefault())
- Timber.d("heartbeat timestamp in UTC is [${timestampZdt}] and local is [$localTime]")
+ Timber.d("requesting permissions")
+ val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
+ permissions.entries.forEach {
+ Timber.d("${it.key} = ${it.value}")
+ }
+ }
- refreshTimestampView.text = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
- }
+ var permissions = arrayOf(
+ Manifest.permission.SEND_SMS,
+ Manifest.permission.RECEIVE_SMS,
+ Manifest.permission.READ_PHONE_NUMBERS,
+ Manifest.permission.READ_SMS,
+ Manifest.permission.READ_PHONE_STATE
+ )
- private fun setVersion() {
- val appVersionView = findViewById<TextView>(R.id.mainAppVersion)
- appVersionView.text = format(getString(R.string.app_version), BuildConfig.VERSION_NAME)
+ if(Build.VERSION.SDK_INT >= 33) {
+ permissions += Manifest.permission.POST_NOTIFICATIONS
+ }
+
+ requestPermissionLauncher.launch(permissions)
+
+ Timber.d("creating permissions launcher")
}
private fun scheduleHeartbeatWorker(context: Context) {
@@ -123,7 +152,7 @@ class MainActivity : AppCompatActivity() {
private fun startStickyNotification(context: Context) {
Timber.d("starting foreground service")
- if(!Settings.getActiveStatus(context)) {
+ if(!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) {
Timber.d("active status is false, not starting foreground service")
return
}
@@ -159,23 +188,21 @@ class MainActivity : AppCompatActivity() {
return
}
+ sendFCMToken(currentTimeStamp, context, Settings.getSIM1PhoneNumber(context), Constants.SIM1)
+ if (Settings.isDualSIM(context)) {
+ sendFCMToken(currentTimeStamp, context, Settings.getSIM2PhoneNumber(context), Constants.SIM2)
+ }
+ }
+
+ private fun sendFCMToken(timestamp: Long, context:Context, phoneNumber: String, sim: String) {
Thread {
- val updated = HttpSmsApiService.create(context).updatePhone(Settings.getSIM1PhoneNumber(context), Settings.getFcmToken(context) ?: "", Constants.SIM1)
+ val updated = HttpSmsApiService.create(context).updatePhone(phoneNumber, Settings.getFcmToken(context) ?: "", sim)
if (updated) {
- Settings.setFcmTokenLastUpdateTimestampAsync(context, currentTimeStamp)
- Timber.i("fcm token uploaded successfully for sim1")
+ Settings.setFcmTokenLastUpdateTimestampAsync(context, timestamp)
+ Timber.i("[${sim}] FCM token uploaded successfully")
return@Thread
- }
- Timber.e("could not update fcm token for sim 1")
-
- if (Settings.isDualSIM(context)) {
- val sim2Updated = HttpSmsApiService.create(context).updatePhone(Settings.getSIM2PhoneNumber(context), Settings.getFcmToken(context) ?: "", Constants.SIM2)
- if (sim2Updated) {
- Settings.setFcmTokenLastUpdateTimestampAsync(context, currentTimeStamp)
- Timber.i("fcm token uploaded successfully for sim2")
- return@Thread
- }
- Timber.e("could not update fcm token for sim 2")
+ } else {
+ Timber.e("[${sim}] could not update FCM token")
}
}.start()
}
@@ -213,14 +240,14 @@ class MainActivity : AppCompatActivity() {
private fun setActiveStatus(context: Context) {
val switch = findViewById<SwitchMaterial>(R.id.cardSwitch)
- switch.isChecked = Settings.getActiveStatus(context)
+ switch.isChecked = Settings.getActiveStatus(context, Constants.SIM1)
switch.setOnCheckedChangeListener{
_, isChecked ->
run {
if (isChecked && !hasAllPermissions(context)) {
Toast.makeText(context, "PERMISSIONS_NOT_GRANTED", Toast.LENGTH_SHORT).show()
} else {
- Settings.setActiveStatusAsync(context, isChecked)
+ Settings.setActiveStatusAsync(context, isChecked, Constants.SIM1)
}
if (isChecked) {
Settings.setIncomingActiveSIM1(context, true)
@@ -228,6 +255,27 @@ class MainActivity : AppCompatActivity() {
}
}
}
+
+ if (!Settings.isDualSIM(context)) {
+ return
+ }
+
+ val switchSIM2 = findViewById<SwitchMaterial>(R.id.cardSwitchSIM2)
+ switchSIM2.isChecked = Settings.getActiveStatus(context, Constants.SIM2)
+ switchSIM2.setOnCheckedChangeListener{
+ _, isChecked ->
+ run {
+ if (isChecked && !hasAllPermissions(context)) {
+ Toast.makeText(context, "PERMISSIONS_NOT_GRANTED", Toast.LENGTH_SHORT).show()
+ } else {
+ Settings.setActiveStatusAsync(context, isChecked, Constants.SIM2)
+ }
+ if (isChecked) {
+ Settings.setIncomingActiveSIM2(context, true)
+ startStickyNotification(context)
+ }
+ }
+ }
}
private fun hasAllPermissions(context: Context): Boolean {
@@ -253,9 +301,26 @@ class MainActivity : AppCompatActivity() {
return false
}
- private fun setOwner(phoneNumber: String) {
- val titleText = findViewById<TextView>(R.id.cardPhoneNumber)
- titleText.text = PhoneNumberUtils.formatNumber(phoneNumber, Locale.getDefault().country)
+ private fun setLastHeartbeatTimestamp(context: Context) {
+ val refreshTimestampView = findViewById<TextView>(R.id.cardRefreshTime)
+ val timestamp = Settings.getHeartbeatTimestamp(context)
+
+ if (timestamp == 0.toLong()) {
+ Timber.d("no heartbeat timestamp has been set")
+ refreshTimestampView.text = "--"
+ return
+ }
+
+ val timestampZdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC)
+ val localTime = timestampZdt.withZoneSameInstant(ZoneId.systemDefault())
+ Timber.d("heartbeat timestamp in UTC is [${timestampZdt}] and local is [$localTime]")
+
+ refreshTimestampView.text = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+
+ if (Settings.isDualSIM(context)) {
+ val refreshTimestampViewSIM2 = findViewById<TextView>(R.id.cardRefreshTimeSIM2)
+ refreshTimestampViewSIM2.text = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ }
}
private fun createChannel() {
@@ -271,40 +336,6 @@ class MainActivity : AppCompatActivity() {
notificationManager.createNotificationChannel(mChannel)
}
- private fun getPhoneNumber(context: Context): String {
- return Settings.getSIM1PhoneNumber(context)
- }
-
- private fun requestPermissions(context:Context) {
- if(!Settings.isLoggedIn(context)) {
- return
- }
-
- Timber.d("requesting permissions")
- val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
- permissions.entries.forEach {
- Timber.d("${it.key} = ${it.value}")
- setOwner(getPhoneNumber(context))
- }
- }
-
- var permissions = arrayOf(
- Manifest.permission.SEND_SMS,
- Manifest.permission.RECEIVE_SMS,
- Manifest.permission.READ_PHONE_NUMBERS,
- Manifest.permission.READ_SMS,
- Manifest.permission.READ_PHONE_STATE
- )
-
- if(Build.VERSION.SDK_INT >= 33) {
- permissions += Manifest.permission.POST_NOTIFICATIONS
- }
-
- requestPermissionLauncher.launch(permissions)
-
- Timber.d("creating permissions launcher")
- }
-
@SuppressLint("BatteryLife")
private fun setBatteryOptimizationListener() {
val pm = getSystemService(POWER_SERVICE) as PowerManager
diff --git a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt b/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt
index 2a9815ff..22b887bc 100644
--- a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt
+++ b/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt
@@ -26,7 +26,7 @@ class ReceivedReceiver: BroadcastReceiver()
var sim = Constants.SIM1
var owner = Settings.getSIM1PhoneNumber(context)
- if (intent.getIntExtra("simSlot", 1) > 1 && Settings.isDualSIM(context)) {
+ if (intent.getIntExtra("android.telephony.extra.SLOT_INDEX", 0) > 0 && Settings.isDualSIM(context)) {
owner = Settings.getSIM2PhoneNumber(context)
sim = Constants.SIM2
}
@@ -38,28 +38,29 @@ class ReceivedReceiver: BroadcastReceiver()
handleMessageReceived(
context,
+ sim,
smsSender,
owner,
smsBody
)
}
- private fun handleMessageReceived(context: Context, from: String, to : String, content: String) {
+ private fun handleMessageReceived(context: Context, sim: String, from: String, to : String, content: String) {
val timestamp = ZonedDateTime.now(ZoneOffset.UTC)
if (!Settings.isLoggedIn(context)) {
- Timber.w("user is not logged in")
+ Timber.w("[${sim}] user is not logged in")
return
}
- if (!Settings.getActiveStatus(context)) {
- Timber.w("user is not active")
+ if (!Settings.getActiveStatus(context, sim)) {
+ Timber.w("[${sim}] user is not active")
return
}
Thread {
- Timber.i("forwarding received message from [${from}]")
- HttpSmsApiService.create(context).receive(from, to, content, timestamp)
+ Timber.i("[${sim}] forwarding received message from [${from}]")
+ HttpSmsApiService.create(context).receive(sim, from, to, content, timestamp)
}.start()
}
}
diff --git a/android/app/src/main/java/com/httpsms/Receiver.kt b/android/app/src/main/java/com/httpsms/Receiver.kt
index 5b0159f0..0fb7fbf2 100644
--- a/android/app/src/main/java/com/httpsms/Receiver.kt
+++ b/android/app/src/main/java/com/httpsms/Receiver.kt
@@ -16,7 +16,7 @@ object Receiver {
return false
}
- if (!Settings.getActiveStatus(context)) {
+ if (!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) {
Timber.w("cannot handle message with id [$messageId] because the user is not active")
return false
}
diff --git a/android/app/src/main/java/com/httpsms/Settings.kt b/android/app/src/main/java/com/httpsms/Settings.kt
index 262a2d71..6a510a37 100644
--- a/android/app/src/main/java/com/httpsms/Settings.kt
+++ b/android/app/src/main/java/com/httpsms/Settings.kt
@@ -94,15 +94,6 @@ object Settings {
.apply()
}
- fun getActiveStatus(context: Context): Boolean {
- val activeStatus = PreferenceManager
- .getDefaultSharedPreferences(context)
- .getBoolean(this.SETTINGS_ACTIVE,true)
-
- Timber.d("SETTINGS_ACTIVE: [$activeStatus]")
- return activeStatus
- }
-
fun isIncomingMessageEnabled(context: Context, sim: String): Boolean {
var setting = this.SETTINGS_SIM1_INCOMING_ACTIVE
if (sim == Constants.SIM2) {
@@ -148,12 +139,17 @@ object Settings {
return activeStatus
}
- fun setActiveStatusAsync(context: Context, status: Boolean) {
+ fun setActiveStatusAsync(context: Context, status: Boolean, sim: String) {
Timber.d(Settings::setActiveStatusAsync.name)
+ var setting = this.SETTINGS_SIM1_ACTIVE
+ if (sim == Constants.SIM2) {
+ setting = this.SETTINGS_SIM2_ACTIVE
+ }
+
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
- .putBoolean(this.SETTINGS_ACTIVE, status)
+ .putBoolean(setting, status)
.apply()
}
diff --git a/android/app/src/main/java/com/httpsms/SettingsActivity.kt b/android/app/src/main/java/com/httpsms/SettingsActivity.kt
index 99659b0f..3d40341b 100644
--- a/android/app/src/main/java/com/httpsms/SettingsActivity.kt
+++ b/android/app/src/main/java/com/httpsms/SettingsActivity.kt
@@ -82,7 +82,8 @@ class SettingsActivity : AppCompatActivity() {
Settings.setApiKeyAsync(this, null)
Settings.setSIM1PhoneNumber(this, null)
Settings.setSIM2PhoneNumber(this, null)
- Settings.setActiveStatusAsync(this, true)
+ Settings.setActiveStatusAsync(this, true, Constants.SIM1)
+ Settings.setActiveStatusAsync(this, true, Constants.SIM2)
Settings.setIncomingActiveSIM1(this, true)
Settings.setIncomingActiveSIM2(this, true)
Settings.setFcmTokenLastUpdateTimestampAsync(this, 0)
diff --git a/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt b/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt
index d158c1ca..e56445e6 100644
--- a/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt
+++ b/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt
@@ -3,6 +3,7 @@ package com.httpsms.worker
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
+import com.httpsms.Constants
import com.httpsms.HttpSmsApiService
import com.httpsms.Settings
import timber.log.Timber
@@ -15,17 +16,37 @@ class HeartbeatWorker(appContext: Context, workerParams: WorkerParameters) : Wor
return Result.failure()
}
- if (!Settings.getActiveStatus(applicationContext)) {
- Timber.w("user is not active, stopping processing")
- return Result.failure()
+ sendSIM1Heartbeat()
+ if (Settings.isDualSIM(applicationContext)) {
+ sendSIM2Heartbeat()
+ }
+
+ return Result.success()
+ }
+
+ private fun sendSIM1Heartbeat() {
+ if (!Settings.getActiveStatus(applicationContext, Constants.SIM1)) {
+ Timber.w("[SIM1]user is not active, stopping processing")
+ return
}
HttpSmsApiService.create(applicationContext).storeHeartbeat(Settings.getSIM1PhoneNumber(applicationContext))
- Timber.d("finished sending heartbeat to server")
+ Timber.d("[SIM1]finished sending heartbeat to server")
Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())
- Timber.d("set the heartbeat timestamp")
+ Timber.d("[SIM1] set the heartbeat timestamp")
+ }
- return Result.success()
+ private fun sendSIM2Heartbeat() {
+ if (!Settings.getActiveStatus(applicationContext, Constants.SIM2)) {
+ Timber.w("[SIM2]user is not active, stopping processing")
+ return
+ }
+
+ HttpSmsApiService.create(applicationContext).storeHeartbeat(Settings.getSIM2PhoneNumber(applicationContext))
+ Timber.d("[SIM2] finished sending heartbeat to server")
+
+ Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis())
+ Timber.d("[SIM2]set the heartbeat timestamp")
}
}
diff --git a/android/app/src/main/res/layout/activity_main.xml b/android/app/src/main/res/layout/activity_main.xml
index cdae886a..5df69ceb 100644
--- a/android/app/src/main/res/layout/activity_main.xml
+++ b/android/app/src/main/res/layout/activity_main.xml
@@ -84,6 +84,60 @@
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
+ <com.google.android.material.card.MaterialCardView
+ android:id="@+id/mainPhoneCardSIM2"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:elevation="16dp"
+ android:layout_marginTop="24dp"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@+id/mainPhoneCard">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:padding="16dp">
+
+ <!-- Title, secondary and supporting text -->
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/cardPhoneNumberSIM2"
+ android:layout_width="wrap_content"
+ android:layout_height="match_parent"
+ android:text="@string/phone_number"
+ android:textAppearance="?attr/textAppearanceTitleMedium"
+ android:textColor="?android:attr/textColorPrimary"
+ android:textSize="28sp" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/cardSwitchSIM2"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:minHeight="48dp"
+ tools:ignore="TouchTargetSizeCheck" />
+ </LinearLayout>
+
+
+ <TextView
+ android:id="@+id/cardRefreshTimeSIM2"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:text="@string/nextRefreshTime"
+ android:textAppearance="?attr/textAppearanceBodyMedium"
+ android:textColor="?android:attr/textColorSecondary"
+ android:textSize="16sp" />
+
+ </LinearLayout>
+ </com.google.android.material.card.MaterialCardView>
+
<LinearLayout
android:id="@+id/batteryOptimizationLinearLayout"
android:layout_width="match_parent"
@@ -93,7 +147,7 @@
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/mainPhoneCard">
+ app:layout_constraintTop_toBottomOf="@+id/mainPhoneCardSIM2">
<com.google.android.material.button.MaterialButton
android:id="@+id/batteryOptimizationButtonButton"
diff --git a/web/models/api.ts b/web/models/api.ts
index 10e5e15d..122645bd 100644
--- a/web/models/api.ts
+++ b/web/models/api.ts
@@ -150,11 +150,9 @@ export interface EntitiesPhone {
fcm_token: string
/** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */
id: string
- /** @example false */
- is_dual_sim: boolean
/**
* MaxSendAttempts determines how many times to retry sending an SMS message
- * @example 1
+ * @example 2
*/
max_send_attempts: number
/** MessageExpirationSeconds is the duration in seconds after sending a message when it is considered to be expired. */
@@ -163,6 +161,7 @@ export interface EntitiesPhone {
messages_per_minute: number
/** @example "+18005550199" */
phone_number: string
+ sim: string
/** @example "2022-06-05T14:26:10.303278+03:00" */
updated_at: string
/** @example "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" */
@@ -196,6 +195,8 @@ export interface EntitiesUser {
subscription_renews_at: string
/** @example "on_trial" */
subscription_status: string
+ /** @example "Europe/Helsinki" */
+ timezone: string
/** @example "2022-06-05T14:26:10.303278+03:00" */
updated_at: string
}
@@ -238,11 +239,6 @@ export interface RequestsMessageBulkSend {
content: string
/** @example "+18005550199" */
from: string
- /**
- * sim card to use to send the message
- * @example "DEFAULT"
- */
- sim: string
/** @example ["+18005550100","+18005550100"] */
to: string[]
}
@@ -272,7 +268,7 @@ export interface RequestsMessageReceive {
from: string
/**
* SIM card that received the message
- * @example "DEFAULT"
+ * @example "SIM1"
*/
sim: string
/**
@@ -289,11 +285,6 @@ export interface RequestsMessageSend {
content: string
/** @example "+18005550199" */
from: string
- /**
- * sim card to use to send the message
- * @example "DEFAULT"
- */
- sim: string
/** @example "+18005550100" */
to: string
}
@@ -306,11 +297,6 @@ export interface RequestsMessageThreadUpdate {
export interface RequestsPhoneUpsert {
/** @example "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." */
fcm_token: string
- /**
- * IsDualSIM is true if the phone has more than one SIM active
- * @example false
- */
- is_dual_sim: boolean
/**
* MaxSendAttempts is the number of attempts when sending an SMS message to handle the case where the phone is offline.
* @example 2
@@ -325,11 +311,18 @@ export interface RequestsPhoneUpsert {
messages_per_minute: number
/** @example "+18005550199" */
phone_number: string
+ /**
+ * SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot
+ * @example "SIM1"
+ */
+ sim: string
}
export interface RequestsUserUpdate {
/** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */
active_phone_id: string
+ /** @example "Europe/Helsinki" */
+ timezone: string
}
export interface RequestsWebhookStore {
diff --git a/web/models/phone.ts b/web/models/phone.ts
deleted file mode 100644
index 520fb2f1..00000000
--- a/web/models/phone.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export interface Phone {
- id: string
- user_id: string
- fcm_token: string
- phone_number: string
- is_dual_sim: boolean
- created_at: string
- updated_at: string
- max_send_attempts: number
- message_expiration_seconds: number
- messages_per_minute: number
-}
diff --git a/web/pages/heartbeats/_id.vue b/web/pages/heartbeats/_id.vue
index 006c10ae..84d1f9d5 100644
--- a/web/pages/heartbeats/_id.vue
+++ b/web/pages/heartbeats/_id.vue
@@ -112,7 +112,7 @@ export default {
dataTableItems() {
return this.heartbeats.map((heartbeat, index) => {
let interval = 0
- if (index < 99) {
+ if (index < this.heartbeats.length - 1) {
interval = this.getDiff(
heartbeat.timestamp,
this.heartbeats[index + 1].timestamp
@@ -143,7 +143,7 @@ export default {
tooltip: {
callbacks: {
label: function (context) {
- if (context.dataIndex === 99) {
+ if (context.dataIndex === context.dataset.data.length - 1) {
return '-'
}
const duration = intervalToDuration({
diff --git a/web/pages/messages/index.vue b/web/pages/messages/index.vue
index 0e544117..cb6b752e 100644
--- a/web/pages/messages/index.vue
+++ b/web/pages/messages/index.vue
@@ -33,23 +33,6 @@
placeholder="Enter your message here"
label="Content"
></v-textarea>
- <div style="width: 175px">
- <v-select
- v-if="$store.getters.getActivePhone.is_dual_sim"
- v-model="simSelected"
- :items="simOptions"
- item-text="title"
- item-value="code"
- persistent-hint
- return-object
- single-line
- solo
- >
- <template #append>
- <v-icon>{{ mdiSim }}</v-icon>
- </template>
- </v-select>
- </div>
<v-btn
type="submit"
class="primary"
diff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vue
index 51655461..258af2ec 100644
--- a/web/pages/settings/index.vue
+++ b/web/pages/settings/index.vue
@@ -320,6 +320,14 @@
:value="activePhone.phone_number"
>
</v-text-field>
+ <v-text-field
+ outlined
+ disabled
+ dense
+ label="SIM"
+ :value="activePhone.sim"
+ >
+ </v-text-field>
<v-textarea
outlined
disabled
diff --git a/web/pages/threads/_id/index.vue b/web/pages/threads/_id/index.vue
index 70515f61..dfa35441 100644
--- a/web/pages/threads/_id/index.vue
+++ b/web/pages/threads/_id/index.vue
@@ -193,30 +193,6 @@
lazy-validation
@submit.prevent="sendMessage"
>
- <v-select
- v-if="$store.getters.getActivePhone.is_dual_sim"
- v-model="simSelected"
- :items="simOptions"
- item-text="title"
- item-value="code"
- class="sim-selector"
- persistent-hint
- return-object
- single-line
- rounded
- filled
- >
- <template #append>
- <v-badge
- :content="simSelected.value"
- :value="simSelected.value > 0"
- :offset-y="10"
- :offset-x="10"
- >
- <v-icon>{{ mdiSim }}</v-icon>
- </v-badge>
- </template>
- </v-select>
<v-text-field
ref="messageInput"
v-model="formMessage"
@@ -493,29 +469,6 @@ export default Vue.extend({
}
}
-.sim-selector {
- max-width: 150px;
-}
-
-@media (max-width: 720px) {
- .sim-selector {
- max-width: 44px;
- }
- .sim-selector .v-select__selections {
- display: none;
- }
- .sim-selector.v-select .v-input__append-inner {
- margin-left: 0;
- }
- .sim-selector.v-text-field--rounded > .v-input__control > .v-input__slot {
- padding-left: 10px;
- padding-right: 10px;
- }
- .sim-selector.v-select .v-input__append-inner {
- padding-left: 0;
- }
-}
-
.no-scrollbar,
.no-scrollbar textarea {
overflow-x: hidden;
diff --git a/web/store/index.ts b/web/store/index.ts
index 6ed03402..6b76e45f 100644
--- a/web/store/index.ts
+++ b/web/store/index.ts
@@ -4,11 +4,11 @@ import { MessageThread } from '~/models/message-thread'
import { Message } from '~/models/message'
import { Heartbeat } from '~/models/heartbeat'
import axios, { setApiKey, setAuthHeader } from '~/plugins/axios'
-import { Phone } from '~/models/phone'
import { User } from '~/models/user'
import { BillingUsage } from '~/models/billing'
import {
EntitiesDiscord,
+ EntitiesPhone,
EntitiesWebhook,
RequestsDiscordStore,
RequestsDiscordUpdate,
@@ -55,7 +55,7 @@ export type State = {
billingUsage: BillingUsage | null
billingUsageHistory: Array<BillingUsage>
user: User | null
- phones: Array<Phone>
+ phones: Array<EntitiesPhone>
threads: Array<MessageThread>
threadId: string | null
heartbeat: null | Heartbeat
@@ -149,15 +149,15 @@ export const getters = {
return state.owner
},
- getActivePhone(state: State): Phone | null {
+ getActivePhone(state: State): EntitiesPhone | null {
return (
- state.phones.find((x: Phone) => {
+ state.phones.find((x: EntitiesPhone) => {
return x.phone_number === state.owner
}) ?? null
)
},
- getPhones(state: State): Array<Phone> {
+ getPhones(state: State): Array<EntitiesPhone> {
return state.phones
},
@@ -233,7 +233,7 @@ export const mutations = {
disableNotification(state: State) {
state.notification.active = false
},
- setPhones(state: State, payload: Array<Phone>) {
+ setPhones(state: State, payload: Array<EntitiesPhone>) {
state.phones = payload
const owner = payload.find((x) => x.phone_number === state.owner)
@@ -327,7 +327,7 @@ export const actions = {
if (context.state.user && context.state.user.active_phone_id) {
const phone = response.data.data.find(
- (x: Phone) => x.id === context.state.user?.active_phone_id
+ (x: EntitiesPhone) => x.id === context.state.user?.active_phone_id
)
if (phone) {
context.commit('setOwner', phone.phone_number)
@@ -349,10 +349,14 @@ export const actions = {
context.commit('resetState', false)
},
- async updatePhone(context: ActionContext<State, State>, phone: Phone) {
+ async updatePhone(
+ context: ActionContext<State, State>,
+ phone: EntitiesPhone
+ ) {
await axios
.put(`/v1/phones`, {
fcm_token: phone.fcm_token,
+ sim: phone.sim,
phone_number: phone.phone_number,
message_expiration_seconds: parseInt(
phone.message_expiration_seconds.toString()
@@ -507,7 +511,7 @@ export const actions = {
])
const phone = context.getters.getPhones.find(
- (x: Phone) => x.id === context.getters.getUser.active_phone_id
+ (x: EntitiesPhone) => x.id === context.getters.getUser.active_phone_id
)
if (phone) {
await context.dispatch('updateUser', {
@@ -559,7 +563,7 @@ export const actions = {
) {
await context.commit('setOwner', payload.owner)
- const phone = context.getters.getActivePhone as Phone | null
+ const phone = context.getters.getActivePhone as EntitiesPhone | null
if (!phone) {
return
}