Simplify API for sending messages

This commit is contained in:
Moez Bhatti
2018-06-27 16:22:42 -04:00
parent e8765a22df
commit 81d77eb1d9
6 changed files with 99 additions and 96 deletions
@@ -206,29 +206,53 @@ class MessageRepositoryImpl @Inject constructor(
}
}
override fun sendSmsAndPersist(subId: Int, threadId: Long, address: String, body: String) {
if (prefs.sendDelay.get() != Preferences.SEND_DELAY_NONE) {
val delay = when (prefs.sendDelay.get()) {
Preferences.SEND_DELAY_SHORT -> 3000
Preferences.SEND_DELAY_MEDIUM -> 5000
Preferences.SEND_DELAY_LONG -> 10000
else -> 0
override fun sendMessage(subId: Int, threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>, delay: Int) {
if (addresses.size == 1 && attachments.isEmpty()) { // SMS
if (delay > 0) { // With delay
val sendTime = System.currentTimeMillis() + delay
val message = insertSentSms(subId, threadId, addresses.first(), body, sendTime)
val intent = getIntentForDelayedSms(message.id)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, sendTime, intent)
} else {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, sendTime, intent)
}
} else { // No delay
val message = insertSentSms(subId, threadId, addresses.first(), body, System.currentTimeMillis())
sendSms(message)
}
} else { // MMS
val settings = Settings().apply { subscriptionId = subId }
val message = com.klinker.android.send_message.Message(body, addresses.toTypedArray())
val sendTime = System.currentTimeMillis() + delay
val message = insertSentSms(subId, threadId, address, body, sendTime)
// Add the GIFs as attachments. The app currently can't compress them, which may result
// in a lot of these messages failing to send
// TODO Add support for GIF compression
attachments
.filter { attachment -> attachment.isGif(context) }
.map { attachment -> attachment.getUri() }
.map { uri -> context.contentResolver.openInputStream(uri) }
.map { inputStream -> inputStream.readBytes() }
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_GIF) }
val intent = getIntentForDelayedSms(message.id)
// Compress the images and add them as attachments
var totalImageBytes = 0
attachments
.filter { attachment -> !attachment.isGif(context) }
.mapNotNull { attachment -> attachment.getUri() }
.mapNotNull { uri -> tryOrNull { imageRepository.loadImage(uri) } }
.also { totalImageBytes = it.sumBy { it.allocationByteCount } }
.map { bitmap ->
val byteRatio = bitmap.allocationByteCount / totalImageBytes.toFloat()
shrink(bitmap, (prefs.mmsSize.get() * 1024 * byteRatio).toInt())
}
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_JPEG) }
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, sendTime, intent)
} else {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, sendTime, intent)
}
} else {
val message = insertSentSms(subId, threadId, address, body, System.currentTimeMillis())
sendSms(message)
val transaction = Transaction(context, settings)
transaction.sendNewMessage(message, threadId)
}
}
@@ -258,37 +282,6 @@ class MessageRepositoryImpl @Inject constructor(
smsManager.sendMultipartTextMessage(message.address, null, parts, ArrayList(sentIntents), ArrayList(deliveredIntents))
}
override fun sendMms(subId: Int, threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>) {
val settings = Settings().apply { subscriptionId = subId }
val message = com.klinker.android.send_message.Message(body, addresses.toTypedArray())
// Add the GIFs as attachments. The app currently can't compress them, which may result
// in a lot of these messages failing to send
// TODO Add support for GIF compression
attachments
.filter { attachment -> attachment.isGif(context) }
.map { attachment -> attachment.getUri() }
.map { uri -> context.contentResolver.openInputStream(uri) }
.map { inputStream -> inputStream.readBytes() }
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_GIF) }
// Compress the images and add them as attachments
var totalImageBytes = 0
attachments
.filter { attachment -> !attachment.isGif(context) }
.mapNotNull { attachment -> attachment.getUri() }
.mapNotNull { uri -> tryOrNull { imageRepository.loadImage(uri) } }
.also { totalImageBytes = it.sumBy { it.allocationByteCount } }
.map { bitmap ->
val byteRatio = bitmap.allocationByteCount / totalImageBytes.toFloat()
shrink(bitmap, (prefs.mmsSize.get() * 1024 * byteRatio).toInt())
}
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_JPEG) }
val transaction = Transaction(context, settings)
transaction.sendNewMessage(message, threadId)
}
private fun shrink(src: Bitmap, maxBytes: Int): ByteArray {
var step = 0.0
val factor = 0.5
@@ -29,22 +29,20 @@ class SendMessage @Inject constructor(
private val messageRepo: MessageRepository
) : Interactor<SendMessage.Params>() {
data class Params(val subId: Int, val threadId: Long, val addresses: List<String>, val body: String, val attachments: List<Attachment> = listOf())
data class Params(
val subId: Int,
val threadId: Long,
val addresses: List<String>,
val body: String,
val attachments: List<Attachment> = listOf(),
val delay: Int = 0)
override fun buildObservable(params: Params): Flowable<Unit> {
return Flowable.just(Unit)
.filter { params.addresses.isNotEmpty() }
.doOnNext {
if (params.addresses.size == 1 && params.attachments.isEmpty()) {
messageRepo.sendSmsAndPersist(params.subId, params.threadId, params.addresses.first(), params.body)
} else {
messageRepo.sendMms(params.subId, params.threadId, params.addresses, params.body, params.attachments)
}
}
// If this was the first message sent in the conversation, the conversation might not exist yet
.doOnNext { conversationRepo.getOrCreateConversation(params.threadId) }
.doOnNext { conversationRepo.updateConversations(params.threadId) }
.doOnNext { conversationRepo.markUnarchived(params.threadId) }
}
override fun buildObservable(params: Params): Flowable<Unit> = Flowable.just(Unit)
.filter { params.addresses.isNotEmpty() }
.doOnNext { messageRepo.sendMessage(params.subId, params.threadId, params.addresses, params.body, params.attachments, params.delay) }
// If this was the first message sent in the conversation, the conversation might not exist yet
.doOnNext { conversationRepo.getOrCreateConversation(params.threadId) }
.doOnNext { conversationRepo.updateConversations(params.threadId) }
.doOnNext { conversationRepo.markUnarchived(params.threadId) }
}
@@ -5,39 +5,35 @@ import android.net.Uri
import com.moez.QKSMS.compat.TelephonyCompat
import com.moez.QKSMS.extensions.mapNotNull
import com.moez.QKSMS.model.Attachment
import com.moez.QKSMS.repository.ConversationRepository
import com.moez.QKSMS.repository.MessageRepository
import com.moez.QKSMS.repository.ScheduledMessageRepository
import io.reactivex.Flowable
import io.reactivex.rxkotlin.toFlowable
import io.realm.RealmList
import javax.inject.Inject
class SendScheduledMessage @Inject constructor(
private val context: Context,
private val conversationRepo: ConversationRepository,
private val messageRepo: MessageRepository,
private val scheduledMessageRepo: ScheduledMessageRepository
private val scheduledMessageRepo: ScheduledMessageRepository,
private val sendMessage: SendMessage
) : Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<*> {
return Flowable.just(params)
.mapNotNull(scheduledMessageRepo::getScheduledMessage)
.map { message ->
TelephonyCompat.getOrCreateThreadId(context, message.recipients).also { threadId ->
if ((message.recipients.size == 1 || !message.sendAsGroup) && message.attachments.isEmpty()) {
message.recipients.forEach { address ->
messageRepo.sendSmsAndPersist(message.subId, threadId, address, message.body)
}
} else {
val attachments = message.attachments.mapNotNull(Uri::parse).map { Attachment(it) }
messageRepo.sendMms(message.subId, threadId, message.recipients, message.body, attachments)
}
}
.flatMap { message ->
if (message.sendAsGroup) {
listOf(message)
} else {
message.recipients.map { recipient -> message.copy(recipients = RealmList(recipient)) }
}.toFlowable()
}
.doOnNext { scheduledMessageRepo.deleteScheduledMessage(params) }
// If this was the first message sent in the conversation, the conversation might not exist yet
.doOnNext { conversationRepo.getOrCreateConversation(it) }
.doOnNext { conversationRepo.updateConversations(it) }
.doOnNext { conversationRepo.markUnarchived(it) }
.map { message ->
val threadId = TelephonyCompat.getOrCreateThreadId(context, message.recipients)
val attachments = message.attachments.mapNotNull(Uri::parse).map { Attachment(it) }
SendMessage.Params(message.subId, threadId, message.recipients, message.body, attachments)
}
.flatMap(sendMessage::buildObservable)
.doFinally { scheduledMessageRepo.deleteScheduledMessage(params) }
}
}
@@ -12,4 +12,17 @@ open class ScheduledMessage(
var sendAsGroup: Boolean = true,
var body: String = "",
var attachments: RealmList<String> = RealmList()
) : RealmObject()
) : RealmObject() {
fun copy(id: Long = this.id,
date: Long = this.date,
subId: Int = this.subId,
recipients: RealmList<String> = this.recipients,
sendAsGroup: Boolean = this.sendAsGroup,
body: String = this.body,
attachments: RealmList<String> = this.attachments): ScheduledMessage {
return ScheduledMessage(id, date, subId, recipients, sendAsGroup, body, attachments)
}
}
@@ -57,18 +57,13 @@ interface MessageRepository {
fun markUnread(vararg threadIds: Long)
/**
* Persists the SMS and attempts to send it
*/
fun sendSmsAndPersist(subId: Int, threadId: Long, address: String, body: String)
fun sendMessage(subId: Int, threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>, delay: Int = 0)
/**
* Attempts to send the SMS message. This can be called if the message has already been persisted
*/
fun sendSms(message: Message)
fun sendMms(subId: Int, threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>)
/**
* Attempts to cancel sending the message with the given id
*/
@@ -54,6 +54,7 @@ import com.moez.QKSMS.repository.ConversationRepository
import com.moez.QKSMS.repository.MessageRepository
import com.moez.QKSMS.repository.ScheduledMessageRepository
import com.moez.QKSMS.util.ActiveSubscriptionObservable
import com.moez.QKSMS.util.Preferences
import com.moez.QKSMS.util.tryOrNull
import com.uber.autodispose.kotlin.autoDisposable
import io.reactivex.Observable
@@ -88,6 +89,7 @@ class ComposeViewModel @Inject constructor(
private val messageRepo: MessageRepository,
private val navigator: Navigator,
private val permissionManager: PermissionManager,
private val prefs: Preferences,
private val retrySending: RetrySending,
private val scheduledMessageRepo: ScheduledMessageRepository,
private val sendMessage: SendMessage,
@@ -559,6 +561,12 @@ class ComposeViewModel @Inject constructor(
true -> conversation.recipients.map { it.address }
false -> contacts.mapNotNull { it.numbers.firstOrNull()?.address }
}
val delay = when (prefs.sendDelay.get()) {
Preferences.SEND_DELAY_SHORT -> 3000
Preferences.SEND_DELAY_MEDIUM -> 5000
Preferences.SEND_DELAY_LONG -> 10000
else -> 0
}
when {
state.scheduled != 0L -> {
@@ -571,7 +579,7 @@ class ComposeViewModel @Inject constructor(
state.sendAsGroup -> {
val threadId = conversation.id.takeIf { it > 0 }
?: TelephonyCompat.getOrCreateThreadId(context, addresses).also(threadIdSubject::onNext)
sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body, attachments))
sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body, attachments, delay))
}
else -> {
@@ -579,7 +587,7 @@ class ComposeViewModel @Inject constructor(
val threadId = TelephonyCompat.getOrCreateThreadId(context, addr)
val address = listOf(conversationRepo.getConversation(threadId)?.recipients?.firstOrNull()?.address
?: addr)
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, attachments))
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, attachments, delay))
}
}
}