Rewrite, move SMS related code into the app
This commit is contained in:
parent
7bce8ab31b
commit
1f36738be0
16 changed files with 647 additions and 162 deletions
|
|
@ -0,0 +1,58 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
import android.content.Context
|
||||
import android.telephony.SmsMessage
|
||||
import android.widget.Toast.LENGTH_LONG
|
||||
import com.klinker.android.send_message.Settings
|
||||
import com.simplemobiletools.commons.extensions.showErrorToast
|
||||
import com.simplemobiletools.commons.extensions.toast
|
||||
import com.simplemobiletools.smsmessenger.R
|
||||
import com.simplemobiletools.smsmessenger.extensions.config
|
||||
import com.simplemobiletools.smsmessenger.extensions.messagingUtils
|
||||
import com.simplemobiletools.smsmessenger.messaging.SmsException.Companion.EMPTY_DESTINATION_ADDRESS
|
||||
import com.simplemobiletools.smsmessenger.messaging.SmsException.Companion.ERROR_PERSISTING_MESSAGE
|
||||
import com.simplemobiletools.smsmessenger.messaging.SmsException.Companion.ERROR_SENDING_MESSAGE
|
||||
import com.simplemobiletools.smsmessenger.models.Attachment
|
||||
|
||||
@Deprecated("TODO: Move/rewrite messaging config code into the app.")
|
||||
fun Context.getSendMessageSettings(): Settings {
|
||||
val settings = Settings()
|
||||
settings.useSystemSending = true
|
||||
settings.deliveryReports = config.enableDeliveryReports
|
||||
settings.sendLongAsMms = config.sendLongMessageMMS
|
||||
settings.sendLongAsMmsAfter = 1
|
||||
settings.group = config.sendGroupMessageMMS
|
||||
return settings
|
||||
}
|
||||
|
||||
fun Context.isLongMmsMessage(text: String, settings: Settings = getSendMessageSettings()): Boolean {
|
||||
val data = SmsMessage.calculateLength(text, false)
|
||||
val numPages = data.first()
|
||||
return numPages > settings.sendLongAsMmsAfter && settings.sendLongAsMms
|
||||
}
|
||||
|
||||
/** Sends the message using the in-app SmsManager API wrappers if it's an SMS or using android-smsmms for MMS. */
|
||||
fun Context.sendMessageCompat(text: String, addresses: List<String>, subId: Int?, attachments: List<Attachment>) {
|
||||
val settings = getSendMessageSettings()
|
||||
if (subId != null) {
|
||||
settings.subscriptionId = subId
|
||||
}
|
||||
|
||||
val isMms = attachments.isNotEmpty() || isLongMmsMessage(text, settings) || addresses.size > 1 && settings.group
|
||||
if (isMms) {
|
||||
messagingUtils.sendMmsMessage(text, addresses, attachments, settings)
|
||||
} else {
|
||||
try {
|
||||
messagingUtils.sendSmsMessage(text, addresses.toSet(), settings.subscriptionId, settings.deliveryReports)
|
||||
} catch (e: SmsException) {
|
||||
when (e.errorCode) {
|
||||
EMPTY_DESTINATION_ADDRESS -> toast(id = R.string.empty_destination_address, length = LENGTH_LONG)
|
||||
ERROR_PERSISTING_MESSAGE -> toast(id = R.string.unable_to_save_message, length = LENGTH_LONG)
|
||||
ERROR_SENDING_MESSAGE -> toast(id = R.string.unknown_error_occurred, length = LENGTH_LONG)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
showErrorToast(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.Telephony.Sms
|
||||
import android.telephony.SmsManager
|
||||
import android.widget.Toast
|
||||
import com.klinker.android.send_message.Message
|
||||
import com.klinker.android.send_message.Settings
|
||||
import com.klinker.android.send_message.Transaction
|
||||
import com.simplemobiletools.commons.extensions.showErrorToast
|
||||
import com.simplemobiletools.commons.extensions.toast
|
||||
import com.simplemobiletools.smsmessenger.R
|
||||
import com.simplemobiletools.smsmessenger.extensions.getThreadId
|
||||
import com.simplemobiletools.smsmessenger.extensions.isPlainTextMimeType
|
||||
import com.simplemobiletools.smsmessenger.extensions.smsSender
|
||||
import com.simplemobiletools.smsmessenger.messaging.SmsException.Companion.ERROR_PERSISTING_MESSAGE
|
||||
import com.simplemobiletools.smsmessenger.models.Attachment
|
||||
|
||||
class MessagingUtils(val context: Context) {
|
||||
|
||||
/**
|
||||
* Insert an SMS to the given URI with thread_id specified.
|
||||
*/
|
||||
private fun insertSmsMessage(
|
||||
subId: Int, dest: String, text: String, timestamp: Long, threadId: Long,
|
||||
status: Int = Sms.STATUS_NONE, type: Int = Sms.MESSAGE_TYPE_OUTBOX
|
||||
): Uri {
|
||||
val response: Uri?
|
||||
val values = ContentValues().apply {
|
||||
put(Sms.ADDRESS, dest)
|
||||
put(Sms.DATE, timestamp)
|
||||
put(Sms.READ, 1)
|
||||
put(Sms.SEEN, 1)
|
||||
put(Sms.BODY, text)
|
||||
|
||||
// insert subscription id only if it is a valid one.
|
||||
if (subId != Settings.DEFAULT_SUBSCRIPTION_ID) {
|
||||
put(Sms.SUBSCRIPTION_ID, subId)
|
||||
}
|
||||
|
||||
if (status != Sms.STATUS_NONE) {
|
||||
put(Sms.STATUS, status)
|
||||
}
|
||||
if (type != Sms.MESSAGE_TYPE_ALL) {
|
||||
put(Sms.TYPE, type)
|
||||
}
|
||||
if (threadId != -1L) {
|
||||
put(Sms.THREAD_ID, threadId)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
response = context.contentResolver.insert(Sms.CONTENT_URI, values)
|
||||
} catch (e: Exception) {
|
||||
throw SmsException(ERROR_PERSISTING_MESSAGE, e)
|
||||
}
|
||||
return response ?: throw SmsException(ERROR_PERSISTING_MESSAGE)
|
||||
}
|
||||
|
||||
/** Send an SMS message given [text] and [addresses]. A [SmsException] is thrown in case any errors occur. */
|
||||
fun sendSmsMessage(
|
||||
text: String, addresses: Set<String>, subId: Int, requireDeliveryReport: Boolean
|
||||
) {
|
||||
if (addresses.size > 1) {
|
||||
// insert a dummy message for this thread if it is a group message
|
||||
val broadCastThreadId = context.getThreadId(addresses.toSet())
|
||||
val mergedAddresses = addresses.joinToString(ADDRESS_SEPARATOR)
|
||||
insertSmsMessage(
|
||||
subId = subId, dest = mergedAddresses, text = text,
|
||||
timestamp = System.currentTimeMillis(), threadId = broadCastThreadId,
|
||||
status = Sms.Sent.STATUS_COMPLETE, type = Sms.Sent.MESSAGE_TYPE_SENT
|
||||
)
|
||||
}
|
||||
|
||||
for (address in addresses) {
|
||||
val threadId = context.getThreadId(address)
|
||||
val messageUri = insertSmsMessage(
|
||||
subId = subId, dest = address, text = text,
|
||||
timestamp = System.currentTimeMillis(), threadId = threadId
|
||||
)
|
||||
context.smsSender.sendMessage(
|
||||
subId = subId, destination = address, body = text, serviceCenter = null,
|
||||
requireDeliveryReport = requireDeliveryReport, messageUri = messageUri
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated("TODO: Move/rewrite MMS code into the app.")
|
||||
fun sendMmsMessage(text: String, addresses: List<String>, attachments: List<Attachment>, settings: Settings) {
|
||||
val transaction = Transaction(context, settings)
|
||||
val message = Message(text, addresses.toTypedArray())
|
||||
|
||||
if (attachments.isNotEmpty()) {
|
||||
for (attachment in attachments) {
|
||||
try {
|
||||
val uri = attachment.getUri()
|
||||
context.contentResolver.openInputStream(uri)?.use {
|
||||
val bytes = it.readBytes()
|
||||
val mimeType = if (attachment.mimetype.isPlainTextMimeType()) {
|
||||
"application/txt"
|
||||
} else {
|
||||
attachment.mimetype
|
||||
}
|
||||
val name = attachment.filename
|
||||
message.addMedia(bytes, mimeType, name, name)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
context.showErrorToast(e)
|
||||
} catch (e: Error) {
|
||||
context.showErrorToast(e.localizedMessage ?: context.getString(R.string.unknown_error_occurred))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
transaction.sendNewMessage(message)
|
||||
} catch (e: Exception) {
|
||||
context.showErrorToast(e)
|
||||
}
|
||||
}
|
||||
|
||||
fun maybeShowErrorToast(resultCode: Int, errorCode: Int) {
|
||||
if (resultCode != Activity.RESULT_OK) {
|
||||
val msgId = if (errorCode != SendStatusReceiver.NO_ERROR_CODE) {
|
||||
context.getString(R.string.carrier_send_error)
|
||||
} else {
|
||||
when (resultCode) {
|
||||
SmsManager.RESULT_ERROR_NO_SERVICE -> context.getString(R.string.error_service_is_unavailable)
|
||||
SmsManager.RESULT_ERROR_RADIO_OFF -> context.getString(R.string.error_radio_turned_off)
|
||||
else -> {
|
||||
context.getString(R.string.unknown_error_occurred_sending_message, resultCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
context.toast(msg = msgId, length = Toast.LENGTH_LONG)
|
||||
} else {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ADDRESS_SEPARATOR = "|"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.app.AlarmManagerCompat
|
||||
import com.simplemobiletools.smsmessenger.helpers.SCHEDULED_MESSAGE_ID
|
||||
import com.simplemobiletools.smsmessenger.helpers.THREAD_ID
|
||||
import com.simplemobiletools.smsmessenger.models.Message
|
||||
import com.simplemobiletools.smsmessenger.receivers.ScheduledMessageReceiver
|
||||
|
||||
/**
|
||||
* All things related to scheduled messages are here.
|
||||
*/
|
||||
|
||||
fun Context.getScheduleSendPendingIntent(message: Message): PendingIntent {
|
||||
val intent = Intent(this, ScheduledMessageReceiver::class.java)
|
||||
intent.putExtra(THREAD_ID, message.threadId)
|
||||
intent.putExtra(SCHEDULED_MESSAGE_ID, message.id)
|
||||
|
||||
val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
return PendingIntent.getBroadcast(this, message.id.toInt(), intent, flags)
|
||||
}
|
||||
|
||||
fun Context.scheduleMessage(message: Message) {
|
||||
val pendingIntent = getScheduleSendPendingIntent(message)
|
||||
val triggerAtMillis = message.millis()
|
||||
|
||||
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent)
|
||||
}
|
||||
|
||||
fun Context.cancelScheduleSendPendingIntent(messageId: Long) {
|
||||
val intent = Intent(this, ScheduledMessageReceiver::class.java)
|
||||
val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
PendingIntent.getBroadcast(this, messageId.toInt(), intent, flags).cancel()
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
|
||||
|
||||
abstract class SendStatusReceiver : BroadcastReceiver() {
|
||||
// Updates the status of the message in the internal database
|
||||
abstract fun updateAndroidDatabase(context: Context, intent: Intent, receiverResultCode: Int)
|
||||
|
||||
// allows the implementer to update the status of the message in their database
|
||||
abstract fun updateAppDatabase(context: Context, intent: Intent, receiverResultCode: Int)
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val resultCode = resultCode
|
||||
ensureBackgroundThread {
|
||||
updateAndroidDatabase(context, intent, resultCode)
|
||||
updateAppDatabase(context, intent, resultCode)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MESSAGE_SENT_ACTION = "com.simplemobiletools.smsmessenger.receiver.SendStatusReceiver.MESSAGE_SENT"
|
||||
const val MESSAGE_DELIVERED_ACTION = "com.simplemobiletools.smsmessenger.receiver.SendStatusReceiver.MESSAGE_DELIVERED"
|
||||
|
||||
// Defined by platform, but no constant provided. See docs for SmsManager.sendTextMessage.
|
||||
const val EXTRA_ERROR_CODE = "errorCode"
|
||||
const val EXTRA_SUB_ID = "subId"
|
||||
|
||||
const val NO_ERROR_CODE = -1
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
class SmsException(val errorCode: Int, val exception: Exception? = null) : Exception() {
|
||||
companion object {
|
||||
const val EMPTY_DESTINATION_ADDRESS = 0
|
||||
const val ERROR_PERSISTING_MESSAGE = 1
|
||||
const val ERROR_SENDING_MESSAGE = 2
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
import android.telephony.SmsManager
|
||||
import com.klinker.android.send_message.Settings
|
||||
|
||||
private var smsManagerInstance: SmsManager? = null
|
||||
private var associatedSubId: Int = -1
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
fun getSmsManager(subId: Int): SmsManager {
|
||||
if (smsManagerInstance == null || subId != associatedSubId) {
|
||||
smsManagerInstance = if (subId != Settings.DEFAULT_SUBSCRIPTION_ID) {
|
||||
try {
|
||||
smsManagerInstance = SmsManager.getSmsManagerForSubscriptionId(subId)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
smsManagerInstance ?: SmsManager.getDefault()
|
||||
} else {
|
||||
SmsManager.getDefault()
|
||||
}
|
||||
associatedSubId = subId
|
||||
}
|
||||
return smsManagerInstance!!
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
package com.simplemobiletools.smsmessenger.messaging
|
||||
|
||||
import android.app.Application
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.telephony.PhoneNumberUtils
|
||||
import com.simplemobiletools.smsmessenger.messaging.SmsException.Companion.EMPTY_DESTINATION_ADDRESS
|
||||
import com.simplemobiletools.smsmessenger.messaging.SmsException.Companion.ERROR_SENDING_MESSAGE
|
||||
import com.simplemobiletools.smsmessenger.receivers.SmsStatusDeliveredReceiver
|
||||
import com.simplemobiletools.smsmessenger.receivers.SmsStatusSentReceiver
|
||||
|
||||
/** Class that sends chat message via SMS. */
|
||||
class SmsSender(val app: Application) {
|
||||
|
||||
// not sure what to do about this yet. this is the default as per android-smsmms
|
||||
private val sendMultipartSmsAsSeparateMessages = false
|
||||
|
||||
// This should be called from a RequestWriter queue thread
|
||||
fun sendMessage(
|
||||
subId: Int, destination: String, body: String, serviceCenter: String?,
|
||||
requireDeliveryReport: Boolean, messageUri: Uri
|
||||
) {
|
||||
var dest = destination
|
||||
if (body.isEmpty()) {
|
||||
throw IllegalArgumentException("SmsSender: empty text message")
|
||||
}
|
||||
// remove spaces and dashes from destination number
|
||||
// (e.g. "801 555 1212" -> "8015551212")
|
||||
// (e.g. "+8211-123-4567" -> "+82111234567")
|
||||
dest = PhoneNumberUtils.stripSeparators(dest)
|
||||
|
||||
if (dest.isEmpty()) {
|
||||
throw SmsException(EMPTY_DESTINATION_ADDRESS)
|
||||
}
|
||||
// Divide the input message by SMS length limit
|
||||
val smsManager = getSmsManager(subId)
|
||||
val messages = smsManager.divideMessage(body)
|
||||
if (messages == null || messages.size < 1) {
|
||||
throw SmsException(ERROR_SENDING_MESSAGE)
|
||||
}
|
||||
// Actually send the sms
|
||||
sendInternal(
|
||||
subId, dest, messages, serviceCenter, requireDeliveryReport, messageUri
|
||||
)
|
||||
}
|
||||
|
||||
// Actually sending the message using SmsManager
|
||||
private fun sendInternal(
|
||||
subId: Int, dest: String,
|
||||
messages: ArrayList<String>, serviceCenter: String?,
|
||||
requireDeliveryReport: Boolean, messageUri: Uri
|
||||
) {
|
||||
val smsManager = getSmsManager(subId)
|
||||
val messageCount = messages.size
|
||||
val deliveryIntents = ArrayList<PendingIntent?>(messageCount)
|
||||
val sentIntents = ArrayList<PendingIntent>(messageCount)
|
||||
|
||||
val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
|
||||
for (i in 0 until messageCount) {
|
||||
// Make pending intents different for each message part
|
||||
val partId = if (messageCount <= 1) 0 else i + 1
|
||||
if (requireDeliveryReport && i == messageCount - 1) {
|
||||
deliveryIntents.add(
|
||||
PendingIntent.getBroadcast(
|
||||
app,
|
||||
partId,
|
||||
getDeliveredStatusIntent(messageUri, subId),
|
||||
flags
|
||||
)
|
||||
)
|
||||
} else {
|
||||
deliveryIntents.add(null)
|
||||
}
|
||||
sentIntents.add(
|
||||
PendingIntent.getBroadcast(
|
||||
app,
|
||||
partId,
|
||||
getSendStatusIntent(messageUri, subId),
|
||||
flags
|
||||
)
|
||||
)
|
||||
}
|
||||
try {
|
||||
if (sendMultipartSmsAsSeparateMessages) {
|
||||
// If multipart sms is not supported, send them as separate messages
|
||||
for (i in 0 until messageCount) {
|
||||
smsManager.sendTextMessage(
|
||||
dest,
|
||||
serviceCenter,
|
||||
messages[i],
|
||||
sentIntents[i],
|
||||
deliveryIntents[i]
|
||||
)
|
||||
}
|
||||
} else {
|
||||
smsManager.sendMultipartTextMessage(
|
||||
dest, serviceCenter, messages, sentIntents, deliveryIntents
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
throw SmsException(ERROR_SENDING_MESSAGE, e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getSendStatusIntent(requestUri: Uri, subId: Int): Intent {
|
||||
val intent = Intent(SendStatusReceiver.MESSAGE_SENT_ACTION, requestUri, app, SmsStatusSentReceiver::class.java)
|
||||
intent.putExtra(SendStatusReceiver.EXTRA_SUB_ID, subId)
|
||||
return intent
|
||||
}
|
||||
|
||||
private fun getDeliveredStatusIntent(requestUri: Uri, subId: Int): Intent {
|
||||
val intent = Intent(SendStatusReceiver.MESSAGE_DELIVERED_ACTION, requestUri, app, SmsStatusDeliveredReceiver::class.java)
|
||||
intent.putExtra(SendStatusReceiver.EXTRA_SUB_ID, subId)
|
||||
return intent
|
||||
}
|
||||
|
||||
companion object {
|
||||
private var instance: SmsSender? = null
|
||||
fun getInstance(app: Application): SmsSender {
|
||||
if (instance == null) {
|
||||
instance = SmsSender(app)
|
||||
}
|
||||
return instance!!
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue