diff --git a/android-smsmms/src/main/java/com/klinker/android/send_message/Settings.kt b/android-smsmms/src/main/java/com/klinker/android/send_message/Settings.kt index 1cfb823e..b6bc1a89 100755 --- a/android-smsmms/src/main/java/com/klinker/android/send_message/Settings.kt +++ b/android-smsmms/src/main/java/com/klinker/android/send_message/Settings.kt @@ -16,8 +16,6 @@ package com.klinker.android.send_message -import android.os.Build - /** * Class to house all of the settings that can be used to send a message */ @@ -39,20 +37,4 @@ class Settings @JvmOverloads constructor( var preText: String? = null, var sendLongAsMms: Boolean = true, var sendLongAsMmsAfter: Int = 3, - subscriptionId: Int = DEFAULT_SUBSCRIPTION_ID) { - - // SIM options - var subscriptionId: Int = subscriptionId - set(value) { - // we won't allow you to go away from the default if your device doesn't support it - field = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1 || false) { - DEFAULT_SUBSCRIPTION_ID - } else { - value - } - } - - companion object { - const val DEFAULT_SUBSCRIPTION_ID = -1 - } -} + var subscriptionId: Int = -1) diff --git a/android-smsmms/src/main/java/com/klinker/android/send_message/SmsManagerFactory.kt b/android-smsmms/src/main/java/com/klinker/android/send_message/SmsManagerFactory.kt index 5f320469..624c75b9 100755 --- a/android-smsmms/src/main/java/com/klinker/android/send_message/SmsManagerFactory.kt +++ b/android-smsmms/src/main/java/com/klinker/android/send_message/SmsManagerFactory.kt @@ -1,6 +1,5 @@ package com.klinker.android.send_message -import android.os.Build import android.telephony.SmsManager object SmsManagerFactory { @@ -10,7 +9,7 @@ object SmsManagerFactory { fun createSmsManager(subscriptionId: Int): SmsManager { var manager: SmsManager? = null - if (subscriptionId != Settings.DEFAULT_SUBSCRIPTION_ID && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { + if (subscriptionId != -1) { try { manager = SmsManager.getSmsManagerForSubscriptionId(subscriptionId) } catch (e: Exception) { diff --git a/data/src/main/java/mapper/CursorToMessageImpl.kt b/data/src/main/java/mapper/CursorToMessageImpl.kt index 040a3a9c..3d956962 100644 --- a/data/src/main/java/mapper/CursorToMessageImpl.kt +++ b/data/src/main/java/mapper/CursorToMessageImpl.kt @@ -85,7 +85,7 @@ class CursorToMessageImpl @Inject constructor( dateSent = cursor.getLong(columnsMap.dateSent) read = cursor.getInt(columnsMap.read) != 0 locked = cursor.getInt(columnsMap.locked) != 0 - subId = cursor.getInt(columnsMap.subId) + subId = if (columnsMap.subId != -1) cursor.getInt(columnsMap.subId) else -1 when (type) { "sms" -> { diff --git a/data/src/main/java/receiver/RemoteMessagingReceiver.kt b/data/src/main/java/receiver/RemoteMessagingReceiver.kt index fa725eb2..a0b7d5d9 100644 --- a/data/src/main/java/receiver/RemoteMessagingReceiver.kt +++ b/data/src/main/java/receiver/RemoteMessagingReceiver.kt @@ -25,24 +25,32 @@ import android.support.v4.app.RemoteInput import dagger.android.AndroidInjection import interactor.MarkRead import interactor.SendMessage +import repository.MessageRepository +import util.SubscriptionUtils import javax.inject.Inject class RemoteMessagingReceiver : BroadcastReceiver() { - @Inject lateinit var sendMessage: SendMessage @Inject lateinit var markRead: MarkRead + @Inject lateinit var messageRepo: MessageRepository + @Inject lateinit var sendMessage: SendMessage + @Inject lateinit var subUtils: SubscriptionUtils override fun onReceive(context: Context, intent: Intent) { AndroidInjection.inject(this, context) - val remoteInput = RemoteInput.getResultsFromIntent(intent) - val bundle = intent.extras - if (remoteInput != null && bundle != null) { - val address = bundle.getString("address") - val threadId = bundle.getLong("threadId") - val body = remoteInput.getCharSequence("body").toString() - markRead.execute(threadId) - sendMessage.execute(SendMessage.Params(threadId, listOf(address), body)) - } + val remoteInput = RemoteInput.getResultsFromIntent(intent) ?: return + val bundle = intent.extras ?: return + + val threadId = bundle.getLong("threadId") + val body = remoteInput.getCharSequence("body").toString() + markRead.execute(threadId) + + val lastMessage = messageRepo.getMessages(threadId).lastOrNull() + val subId = subUtils.subscriptions.firstOrNull { it.subscriptionId == lastMessage?.subId }?.subscriptionId ?: -1 + val addresses = messageRepo.getConversation(threadId)?.recipients?.map { it.address } ?: return + + val pendingRepository = goAsync() + sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body)) { pendingRepository.finish() } } } diff --git a/data/src/main/java/receiver/SmsReceiver.kt b/data/src/main/java/receiver/SmsReceiver.kt index 9c1b0644..18ec968b 100644 --- a/data/src/main/java/receiver/SmsReceiver.kt +++ b/data/src/main/java/receiver/SmsReceiver.kt @@ -34,8 +34,10 @@ class SmsReceiver : BroadcastReceiver() { AndroidInjection.inject(this, context) Sms.Intents.getMessagesFromIntent(intent)?.let { messages -> + val subId = intent.extras?.getInt("subscription", -1) ?: -1 + val pendingResult = goAsync() - receiveMessage.execute(messages, { pendingResult.finish() }) + receiveMessage.execute(ReceiveSms.Params(subId, messages), { pendingResult.finish() }) } } diff --git a/data/src/main/java/repository/MessageRepositoryImpl.kt b/data/src/main/java/repository/MessageRepositoryImpl.kt index 0852831f..0088289e 100644 --- a/data/src/main/java/repository/MessageRepositoryImpl.kt +++ b/data/src/main/java/repository/MessageRepositoryImpl.kt @@ -393,7 +393,7 @@ class MessageRepositoryImpl @Inject constructor( } } - override fun sendSmsAndPersist(threadId: Long, address: String, body: String) { + 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 @@ -403,7 +403,7 @@ class MessageRepositoryImpl @Inject constructor( } val sendTime = System.currentTimeMillis() + delay - val message = insertSentSms(threadId, address, body, sendTime) + val message = insertSentSms(subId, threadId, address, body, sendTime) val intent = getIntentForDelayedSms(message.id) @@ -414,13 +414,13 @@ class MessageRepositoryImpl @Inject constructor( alarmManager.setExact(AlarmManager.RTC_WAKEUP, sendTime, intent) } } else { - val message = insertSentSms(threadId, address, body, System.currentTimeMillis()) + val message = insertSentSms(subId, threadId, address, body, System.currentTimeMillis()) sendSms(message) } } override fun sendSms(message: Message) { - val smsManager = SmsManager.getDefault() + val smsManager = SmsManager.getSmsManagerForSubscriptionId(message.subId) val parts = smsManager.divideMessage(if (prefs.unicode.get()) StripAccents.stripAccents(message.body) else message.body) ?: arrayListOf() @@ -443,8 +443,8 @@ class MessageRepositoryImpl @Inject constructor( smsManager.sendMultipartTextMessage(message.address, null, parts, ArrayList(sentIntents), ArrayList(deliveredIntents)) } - override fun sendMms(threadId: Long, addresses: List, body: String, attachments: List) { - val settings = Settings() + override fun sendMms(subId: Int, threadId: Long, addresses: List, body: String, attachments: List) { + 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 @@ -509,7 +509,7 @@ class MessageRepositoryImpl @Inject constructor( return PendingIntent.getBroadcast(context, id.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT) } - override fun insertSentSms(threadId: Long, address: String, body: String, date: Long): Message { + override fun insertSentSms(subId: Int, threadId: Long, address: String, body: String, date: Long): Message { // Insert the message to Realm val message = Message().apply { @@ -517,6 +517,7 @@ class MessageRepositoryImpl @Inject constructor( this.address = address this.body = body this.date = date + this.subId = subId id = messageIds.newId() boxId = Telephony.Sms.MESSAGE_TYPE_OUTBOX @@ -537,6 +538,7 @@ class MessageRepositoryImpl @Inject constructor( put(Telephony.Sms.SEEN, true) put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_OUTBOX) put(Telephony.Sms.THREAD_ID, threadId) + put(Telephony.Sms.SUBSCRIPTION_ID, subId) } val uri = context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values) @@ -548,7 +550,7 @@ class MessageRepositoryImpl @Inject constructor( return message } - override fun insertReceivedSms(address: String, body: String, sentTime: Long): Message { + override fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long): Message { // Insert the message to Realm val message = Message().apply { @@ -556,6 +558,7 @@ class MessageRepositoryImpl @Inject constructor( this.body = body this.dateSent = sentTime this.date = System.currentTimeMillis() + this.subId = subId id = messageIds.newId() threadId = getOrCreateConversation(address).blockingGet().id @@ -571,6 +574,7 @@ class MessageRepositoryImpl @Inject constructor( put(Telephony.Sms.ADDRESS, address) put(Telephony.Sms.BODY, body) put(Telephony.Sms.DATE_SENT, sentTime) + put(Telephony.Sms.SUBSCRIPTION_ID, subId) } val uri = context.contentResolver.insert(Telephony.Sms.Inbox.CONTENT_URI, values) diff --git a/data/src/main/java/service/HeadlessSmsSendService.kt b/data/src/main/java/service/HeadlessSmsSendService.kt index e2c66610..15e498a6 100644 --- a/data/src/main/java/service/HeadlessSmsSendService.kt +++ b/data/src/main/java/service/HeadlessSmsSendService.kt @@ -40,7 +40,7 @@ class HeadlessSmsSendService : IntentService("HeadlessSmsSendService") { val intentUri = intent.data val recipients = getRecipients(intentUri).split(";") val threadId = messageRepo.getOrCreateConversation(recipients).blockingGet()?.id ?: 0L - sendMessage.execute(SendMessage.Params(threadId, recipients, body)) + sendMessage.execute(SendMessage.Params(-1, threadId, recipients, body)) } } diff --git a/data/src/main/java/util/ActiveSubscriptionObservable.kt b/data/src/main/java/util/ActiveSubscriptionObservable.kt new file mode 100644 index 00000000..9f2792c3 --- /dev/null +++ b/data/src/main/java/util/ActiveSubscriptionObservable.kt @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2017 Moez Bhatti + * + * This file is part of QKSMS. + * + * QKSMS is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * QKSMS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with QKSMS. If not, see . + */ +package util + +import android.telephony.SubscriptionInfo +import android.telephony.SubscriptionManager +import io.reactivex.Observable +import io.reactivex.Observer +import io.reactivex.disposables.Disposable + +class ActiveSubscriptionObservable(private val subscriptionManager: SubscriptionManager) : Observable>() { + + override fun subscribeActual(observer: Observer>) { + observer.onNext(subscriptionManager.activeSubscriptionInfoList ?: listOf()) + + val listener = Listener(subscriptionManager, observer) + observer.onSubscribe(listener) + subscriptionManager.addOnSubscriptionsChangedListener(listener) + } + + internal class Listener( + private val subscriptionManager: SubscriptionManager, + private val observer: Observer> + ) : Disposable, SubscriptionManager.OnSubscriptionsChangedListener() { + + private var disposed: Boolean = false + + override fun onSubscriptionsChanged() { + if (!isDisposed) { + observer.onNext(subscriptionManager.activeSubscriptionInfoList ?: listOf()) + } + } + + override fun isDisposed(): Boolean = disposed + + override fun dispose() { + disposed = true + subscriptionManager.removeOnSubscriptionsChangedListener(this) + } + + } + +} \ No newline at end of file diff --git a/data/src/main/java/util/SubscriptionUtilsImpl.kt b/data/src/main/java/util/SubscriptionUtilsImpl.kt new file mode 100644 index 00000000..4356272a --- /dev/null +++ b/data/src/main/java/util/SubscriptionUtilsImpl.kt @@ -0,0 +1,23 @@ +package util + +import android.content.Context +import android.telephony.PhoneNumberUtils +import android.telephony.SubscriptionInfo +import android.telephony.SubscriptionManager +import io.reactivex.Observable +import javax.inject.Inject + +class SubscriptionUtilsImpl @Inject constructor(context: Context) : SubscriptionUtils { + + private val subscriptionManager = SubscriptionManager.from(context) + + override val subscriptions: List + get() = subscriptionManager.activeSubscriptionInfoList ?: listOf() + + override val subscriptionsObservable: Observable> = ActiveSubscriptionObservable(subscriptionManager) + + override fun getSubIdForAddress(address: String): Int { + return subscriptions.firstOrNull { PhoneNumberUtils.compare(it.number, address) }?.subscriptionId ?: -1 + } + +} \ No newline at end of file diff --git a/domain/src/main/java/interactor/ReceiveSms.kt b/domain/src/main/java/interactor/ReceiveSms.kt index 411951fd..4ad37861 100644 --- a/domain/src/main/java/interactor/ReceiveSms.kt +++ b/domain/src/main/java/interactor/ReceiveSms.kt @@ -32,23 +32,26 @@ class ReceiveSms @Inject constructor( private val messageRepo: MessageRepository, private val notificationManager: NotificationManager, private val updateBadge: UpdateBadge -) : Interactor>() { +) : Interactor() { - override fun buildObservable(params: Array): Flowable<*> { + class Params(val subId: Int, val messages: Array) + + override fun buildObservable(params: Params): Flowable<*> { return Flowable.just(params) - .filter { it.isNotEmpty() } - .filter { messages -> // Don't continue if the sender is blocked - val address = messages[0].displayOriginatingAddress + .filter { it.messages.isNotEmpty() } + .filter { // Don't continue if the sender is blocked + val address = it.messages[0].displayOriginatingAddress !externalBlockingManager.shouldBlock(address).blockingGet() } - .map { messages -> + .map { + val messages = it.messages val address = messages[0].displayOriginatingAddress val time = messages[0].timestampMillis val body: String = messages .map { message -> message.displayMessageBody } .reduce { body, new -> body + new } - messageRepo.insertReceivedSms(address, body, time) // Add the message to the db + messageRepo.insertReceivedSms(it.subId, address, body, time) // Add the message to the db } .doOnNext { message -> messageRepo.updateConversations(message.threadId) } // Update the conversation .mapNotNull { message -> messageRepo.getOrCreateConversation(message.threadId) } // Map message to conversation diff --git a/domain/src/main/java/interactor/RetrySending.kt b/domain/src/main/java/interactor/RetrySending.kt index 05541b25..2ffb52f5 100644 --- a/domain/src/main/java/interactor/RetrySending.kt +++ b/domain/src/main/java/interactor/RetrySending.kt @@ -34,6 +34,7 @@ class RetrySending @Inject constructor(private val messageRepo: MessageRepositor type = params.type address = params.address body = params.body + subId = params.subId } return Flowable.just(message) diff --git a/domain/src/main/java/interactor/SendMessage.kt b/domain/src/main/java/interactor/SendMessage.kt index e03e24ae..5b1b574c 100644 --- a/domain/src/main/java/interactor/SendMessage.kt +++ b/domain/src/main/java/interactor/SendMessage.kt @@ -27,16 +27,16 @@ class SendMessage @Inject constructor( private val messageRepo: MessageRepository ) : Interactor() { - data class Params(val threadId: Long, val addresses: List, val body: String, val attachments: List = listOf()) + data class Params(val subId: Int, val threadId: Long, val addresses: List, val body: String, val attachments: List = listOf()) override fun buildObservable(params: Params): Flowable { return Flowable.just(Unit) .filter { params.addresses.isNotEmpty() } .doOnNext { if (params.addresses.size == 1 && params.attachments.isEmpty()) { - messageRepo.sendSmsAndPersist(params.threadId, params.addresses.first(), params.body) + messageRepo.sendSmsAndPersist(params.subId, params.threadId, params.addresses.first(), params.body) } else { - messageRepo.sendMms(params.threadId, params.addresses, params.body, params.attachments) + messageRepo.sendMms(params.subId, params.threadId, params.addresses, params.body, params.attachments) } } .doOnNext { messageRepo.updateConversations(params.threadId) } diff --git a/domain/src/main/java/model/Message.kt b/domain/src/main/java/model/Message.kt index 6e48a7b7..7dd55823 100644 --- a/domain/src/main/java/model/Message.kt +++ b/domain/src/main/java/model/Message.kt @@ -154,7 +154,9 @@ open class Message : RealmObject() { return isFailedMms || isFailedSms } - fun compareSender(other: Message): Boolean { - return isMe() && other.isMe() || (!isMe() && !other.isMe() && address == other.address) + fun compareSender(other: Message): Boolean = when { + isMe() && other.isMe() -> subId == other.subId + !isMe() && !other.isMe() -> subId == other.subId && address == other.address + else -> false } } \ No newline at end of file diff --git a/domain/src/main/java/repository/MessageRepository.kt b/domain/src/main/java/repository/MessageRepository.kt index bd76cc3e..e2d39fcf 100644 --- a/domain/src/main/java/repository/MessageRepository.kt +++ b/domain/src/main/java/repository/MessageRepository.kt @@ -94,23 +94,23 @@ interface MessageRepository { /** * Persists the SMS and attempts to send it */ - fun sendSmsAndPersist(threadId: Long, address: String, body: String) + fun sendSmsAndPersist(subId: Int, threadId: Long, address: String, body: String) /** * Attempts to send the SMS message. This can be called if the message has already been persisted */ fun sendSms(message: Message) - fun sendMms(threadId: Long, addresses: List, body: String, attachments: List) + fun sendMms(subId: Int, threadId: Long, addresses: List, body: String, attachments: List) /** * Attempts to cancel sending the message with the given id */ fun cancelDelayedSms(id: Long) - fun insertSentSms(threadId: Long, address: String, body: String, date: Long): Message + fun insertSentSms(subId: Int, threadId: Long, address: String, body: String, date: Long): Message - fun insertReceivedSms(address: String, body: String, sentTime: Long): Message + fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long): Message /** * Marks the message as sending, in case we need to retry sending it diff --git a/domain/src/main/java/util/SubscriptionUtils.kt b/domain/src/main/java/util/SubscriptionUtils.kt new file mode 100644 index 00000000..62759c0d --- /dev/null +++ b/domain/src/main/java/util/SubscriptionUtils.kt @@ -0,0 +1,14 @@ +package util + +import android.telephony.SubscriptionInfo +import io.reactivex.Observable + +interface SubscriptionUtils { + + val subscriptions: List + + val subscriptionsObservable: Observable> + + fun getSubIdForAddress(address: String): Int + +} \ No newline at end of file diff --git a/presentation/src/main/java/common/util/NotificationManagerImpl.kt b/presentation/src/main/java/common/util/NotificationManagerImpl.kt index b85a5da7..d63a4092 100644 --- a/presentation/src/main/java/common/util/NotificationManagerImpl.kt +++ b/presentation/src/main/java/common/util/NotificationManagerImpl.kt @@ -172,7 +172,7 @@ class NotificationManagerImpl @Inject constructor( .forEach { uri -> notification.addPerson(uri) } if (Build.VERSION.SDK_INT >= 24) { - notification.addAction(getReplyAction(conversation.recipients[0]?.address.orEmpty(), threadId)) + notification.addAction(getReplyAction(threadId)) } else { val replyIntent = Intent(context, QkReplyActivity::class.java).putExtra("threadId", threadId) val replyPI = PendingIntent.getActivity(context, threadId.toInt() + 40000, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT) @@ -224,10 +224,8 @@ class NotificationManagerImpl @Inject constructor( notificationManager.notify(threadId.toInt() + 50000, notification.build()) } - private fun getReplyAction(address: String, threadId: Long): NotificationCompat.Action { - val replyIntent = Intent(context, RemoteMessagingReceiver::class.java) - .putExtra("address", address) - .putExtra("threadId", threadId) + private fun getReplyAction(threadId: Long): NotificationCompat.Action { + val replyIntent = Intent(context, RemoteMessagingReceiver::class.java).putExtra("threadId", threadId) val replyPI = PendingIntent.getBroadcast(context, threadId.toInt() + 40000, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT) val responseSet = context.resources.getStringArray(R.array.qk_responses) diff --git a/presentation/src/main/java/feature/compose/ComposeActivity.kt b/presentation/src/main/java/feature/compose/ComposeActivity.kt index 0bf5ea52..80dbe375 100644 --- a/presentation/src/main/java/feature/compose/ComposeActivity.kt +++ b/presentation/src/main/java/feature/compose/ComposeActivity.kt @@ -89,12 +89,13 @@ class ComposeActivity : QkThemedActivity(), ComposeView { override val galleryIntent by lazy { gallery.clicks() } override val attachmentSelectedIntent: Subject = PublishSubject.create() override val inputContentIntent by lazy { message.inputContentSelected } + override val changeSimIntent by lazy { sim.clicks() } override val sendIntent by lazy { send.clicks() } override val backPressedIntent: Subject = PublishSubject.create() private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory)[ComposeViewModel::class.java] } - var cameraDestination: Uri? = null + private var cameraDestination: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) @@ -197,6 +198,9 @@ class ComposeActivity : QkThemedActivity(), ComposeView { counter.text = state.remaining counter.setVisible(counter.text.isNotBlank()) + sim.setVisible(state.subscription != null) + simIndex.text = "${state.subscription?.simSlotIndex?.plus(1)}" + send.isEnabled = state.canSend send.imageAlpha = if (state.canSend) 255 else 128 } diff --git a/presentation/src/main/java/feature/compose/ComposeState.kt b/presentation/src/main/java/feature/compose/ComposeState.kt index 7c3a9186..4ddfca2a 100644 --- a/presentation/src/main/java/feature/compose/ComposeState.kt +++ b/presentation/src/main/java/feature/compose/ComposeState.kt @@ -18,6 +18,7 @@ */ package feature.compose +import android.telephony.SubscriptionInfo import io.realm.RealmResults import model.Attachment import model.Contact @@ -41,5 +42,6 @@ data class ComposeState( val attachments: List = ArrayList(), val attaching: Boolean = false, val remaining: String = "", + val subscription: SubscriptionInfo? = null, val canSend: Boolean = false ) \ No newline at end of file diff --git a/presentation/src/main/java/feature/compose/ComposeView.kt b/presentation/src/main/java/feature/compose/ComposeView.kt index 21455250..28186229 100644 --- a/presentation/src/main/java/feature/compose/ComposeView.kt +++ b/presentation/src/main/java/feature/compose/ComposeView.kt @@ -47,6 +47,7 @@ interface ComposeView : QkView { val galleryIntent: Observable<*> val attachmentSelectedIntent: Observable val inputContentIntent: Observable + val changeSimIntent: Observable<*> val sendIntent: Observable fun clearSelection() diff --git a/presentation/src/main/java/feature/compose/ComposeViewModel.kt b/presentation/src/main/java/feature/compose/ComposeViewModel.kt index bed6ab45..67f9c61a 100644 --- a/presentation/src/main/java/feature/compose/ComposeViewModel.kt +++ b/presentation/src/main/java/feature/compose/ComposeViewModel.kt @@ -56,6 +56,7 @@ import model.Message import model.PhoneNumber import repository.ContactRepository import repository.MessageRepository +import util.SubscriptionUtils import util.extensions.asObservable import util.extensions.isImage import util.extensions.mapNotNull @@ -79,6 +80,7 @@ class ComposeViewModel @Inject constructor( private val permissionManager: PermissionManager, private val retrySending: RetrySending, private val sendMessage: SendMessage, + private val subUtils: SubscriptionUtils, private val syncContacts: ContactSync ) : QkViewModel(ComposeState(query = intent.extras?.getString("query") ?: "")) { @@ -196,6 +198,15 @@ class ComposeViewModel @Inject constructor( } }.subscribe() + val latestSubId = messages + .map { messages -> messages.lastOrNull()?.subId ?: -1 } + .distinctUntilChanged() + + disposables += Observables.combineLatest(latestSubId, subUtils.subscriptionsObservable) { subId, subs -> + val sub = if (subs.size > 1) subs.firstOrNull { it.subscriptionId == subId } ?: subs[0] else null + newState { it.copy(subscription = sub) } + }.subscribe() + if (threadId == 0L) { syncContacts.execute(Unit) } @@ -494,14 +505,30 @@ class ComposeViewModel @Inject constructor( .autoDisposable(view.scope()) .subscribe { remaining -> newState { it.copy(remaining = remaining) } } + // Toggle to the next sim slot + view.changeSimIntent + .withLatestFrom(state) { _, state -> + val subs = subUtils.subscriptions + val subIndex = subs.indexOfFirst { it.subscriptionId == state.subscription?.subscriptionId } + val subscription = when { + subIndex == -1 -> null + subIndex < subs.size - 1 -> subs[subIndex + 1] + else -> subs[0] + } + newState { it.copy(subscription = subscription) } + } + .autoDisposable(view.scope()) + .subscribe() + // Send a message when the send button is clicked, and disable editing mode if it's enabled view.sendIntent .withLatestFrom(view.textChangedIntent, { _, body -> body }) .map { body -> body.toString() } - .withLatestFrom(attachments, conversation, { body, attachments, conversation -> + .withLatestFrom(state, attachments, conversation, { body, state, attachments, conversation -> + val subId = state.subscription?.subscriptionId ?: -1 val threadId = conversation.id val addresses = conversation.recipients.map { it.address } - sendMessage.execute(SendMessage.Params(threadId, addresses, body, attachments)) + sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body, attachments)) view.setDraft("") this.attachments.onNext(ArrayList()) }) diff --git a/presentation/src/main/java/feature/compose/MessagesAdapter.kt b/presentation/src/main/java/feature/compose/MessagesAdapter.kt index 6974ec91..168c2605 100644 --- a/presentation/src/main/java/feature/compose/MessagesAdapter.kt +++ b/presentation/src/main/java/feature/compose/MessagesAdapter.kt @@ -21,7 +21,6 @@ package feature.compose import android.animation.ObjectAnimator import android.content.Context import android.graphics.Typeface -import android.os.Build import android.support.v7.widget.RecyclerView import android.telephony.PhoneNumberUtils import android.text.Spannable @@ -43,7 +42,6 @@ import common.util.DateFormatter import common.util.GlideApp import common.util.extensions.dpToPx import common.util.extensions.forwardTouches -import common.util.extensions.resolveThemeColor import common.util.extensions.setBackgroundTint import common.util.extensions.setPadding import common.util.extensions.setTint @@ -59,6 +57,7 @@ import model.Conversation import model.Message import model.Recipient import util.Preferences +import util.SubscriptionUtils import util.extensions.hasThumbnails import util.extensions.isImage import util.extensions.isVideo @@ -70,7 +69,8 @@ class MessagesAdapter @Inject constructor( private val colors: Colors, private val dateFormatter: DateFormatter, private val navigator: Navigator, - private val prefs: Preferences + private val prefs: Preferences, + private val subUtils: SubscriptionUtils ) : QkRealmAdapter() { companion object { @@ -116,6 +116,7 @@ class MessagesAdapter @Inject constructor( private val contactCache = ContactCache() private val expanded = HashMap() private val disposables = CompositeDisposable() + private val subs = subUtils.subscriptions var theme: Colors.Theme = colors.theme() @@ -206,8 +207,14 @@ class MessagesAdapter @Inject constructor( // Bind the timestamp val timeSincePrevious = TimeUnit.MILLISECONDS.toMinutes(message.date - (previous?.date ?: 0)) + val simIndex = subs.takeIf { it.size > 1 }?.indexOfFirst { it.subscriptionId == message.subId } ?: -1 + view.timestamp.text = dateFormatter.getMessageTimestamp(message.date) - view.timestamp.visibility = if (timeSincePrevious < TIMESTAMP_THRESHOLD) View.GONE else View.VISIBLE + view.simIndex.text = "${simIndex + 1}" + + view.timestamp.setVisible(timeSincePrevious >= TIMESTAMP_THRESHOLD || message.subId != previous?.subId && simIndex != -1) + view.sim.setVisible(message.subId != previous?.subId && simIndex != -1) + view.simIndex.setVisible(message.subId != previous?.subId && simIndex != -1) // Bind the grouping @@ -283,15 +290,6 @@ class MessagesAdapter @Inject constructor( GlideApp.with(context).load(part.getUri()).fitCenter().into(mediaView.thumbnail) view.attachments.addView(mediaView) } - - - // If we're on API 21, we need to re-tint the background - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) { - view.body.setBackgroundTint(when (message.isMe()) { - true -> context.resolveThemeColor(R.attr.bubbleColor) - false -> theme.theme - }) - } } private fun bindStatus(viewHolder: QkViewHolder, message: Message, next: Message?) { diff --git a/presentation/src/main/java/feature/qkreply/QkReplyActivity.kt b/presentation/src/main/java/feature/qkreply/QkReplyActivity.kt index d05aaee1..bcf16622 100644 --- a/presentation/src/main/java/feature/qkreply/QkReplyActivity.kt +++ b/presentation/src/main/java/feature/qkreply/QkReplyActivity.kt @@ -30,7 +30,6 @@ import android.view.WindowManager import com.jakewharton.rxbinding2.view.clicks import com.jakewharton.rxbinding2.widget.textChanges import com.moez.QKSMS.R -import com.moez.QKSMS.R.id.* import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.kotlin.autoDisposable import common.base.QkThemedActivity @@ -52,6 +51,7 @@ class QkReplyActivity : QkThemedActivity(), QkReplyView { override val menuItemIntent: Subject = PublishSubject.create() override val textChangedIntent by lazy { message.textChanges() } + override val changeSimIntent by lazy { sim.clicks() } override val sendIntent by lazy { send.clicks() } private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory)[QkReplyViewModel::class.java] } @@ -99,6 +99,9 @@ class QkReplyActivity : QkThemedActivity(), QkReplyView { counter.text = state.remaining counter.setVisible(counter.text.isNotBlank()) + sim.setVisible(state.subscription != null) + simIndex.text = "${state.subscription?.simSlotIndex?.plus(1)}" + send.isEnabled = state.canSend send.imageAlpha = if (state.canSend) 255 else 128 } diff --git a/presentation/src/main/java/feature/qkreply/QkReplyActivityModule.kt b/presentation/src/main/java/feature/qkreply/QkReplyActivityModule.kt index f57e8982..24dbad95 100644 --- a/presentation/src/main/java/feature/qkreply/QkReplyActivityModule.kt +++ b/presentation/src/main/java/feature/qkreply/QkReplyActivityModule.kt @@ -1,17 +1,18 @@ package feature.qkreply import android.arch.lifecycle.ViewModel -import android.content.Intent import dagger.Module import dagger.Provides import dagger.multibindings.IntoMap import injection.ViewModelKey +import javax.inject.Named @Module class QkReplyActivityModule { @Provides - fun provideIntent(activity: QkReplyActivity): Intent = activity.intent + @Named("threadId") + fun provideThreadId(activity: QkReplyActivity): Long = activity.intent.extras?.getLong("threadId") ?: 0L @Provides @IntoMap diff --git a/presentation/src/main/java/feature/qkreply/QkReplyState.kt b/presentation/src/main/java/feature/qkreply/QkReplyState.kt index f4cc4cd6..1f4a8feb 100644 --- a/presentation/src/main/java/feature/qkreply/QkReplyState.kt +++ b/presentation/src/main/java/feature/qkreply/QkReplyState.kt @@ -18,6 +18,7 @@ */ package feature.qkreply +import android.telephony.SubscriptionInfo import io.realm.RealmResults import model.Conversation import model.Message @@ -28,5 +29,6 @@ data class QkReplyState( val expanded: Boolean = false, val data: Pair>? = null, val remaining: String = "", + val subscription: SubscriptionInfo? = null, val canSend: Boolean = false ) \ No newline at end of file diff --git a/presentation/src/main/java/feature/qkreply/QkReplyView.kt b/presentation/src/main/java/feature/qkreply/QkReplyView.kt index ebe565b9..5a31fc74 100644 --- a/presentation/src/main/java/feature/qkreply/QkReplyView.kt +++ b/presentation/src/main/java/feature/qkreply/QkReplyView.kt @@ -25,6 +25,7 @@ interface QkReplyView : QkView { val menuItemIntent: Observable val textChangedIntent: Observable + val changeSimIntent: Observable<*> val sendIntent: Observable fun setDraft(draft: String) diff --git a/presentation/src/main/java/feature/qkreply/QkReplyViewModel.kt b/presentation/src/main/java/feature/qkreply/QkReplyViewModel.kt index a591b1d0..a35c81eb 100644 --- a/presentation/src/main/java/feature/qkreply/QkReplyViewModel.kt +++ b/presentation/src/main/java/feature/qkreply/QkReplyViewModel.kt @@ -18,7 +18,6 @@ */ package feature.qkreply -import android.content.Intent import android.telephony.SmsMessage import com.moez.QKSMS.R import com.uber.autodispose.android.lifecycle.scope @@ -27,37 +26,42 @@ import common.Navigator import common.base.QkViewModel import interactor.MarkRead import interactor.SendMessage +import io.reactivex.rxkotlin.Observables import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.withLatestFrom import io.reactivex.schedulers.Schedulers -import io.reactivex.subjects.PublishSubject +import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.Subject import io.realm.RealmResults import model.Conversation import model.Message import repository.MessageRepository +import util.SubscriptionUtils import util.extensions.asObservable import util.extensions.mapNotNull import java.util.concurrent.TimeUnit import javax.inject.Inject +import javax.inject.Named class QkReplyViewModel @Inject constructor( - private val intent: Intent, + @Named("threadId") threadId: Long, private val markRead: MarkRead, private val messageRepo: MessageRepository, private val navigator: Navigator, - private val sendMessage: SendMessage + private val sendMessage: SendMessage, + private val subUtils: SubscriptionUtils ) : QkViewModel(QkReplyState()) { private val conversation by lazy { - messageRepo.getConversationAsync(intent.getLongExtra("threadId", -1)) + messageRepo.getConversationAsync(threadId) .asObservable() .filter { it.isLoaded } .filter { it.isValid } .distinctUntilChanged() } - private val messages: Subject> = PublishSubject.create() + private val messages: Subject> = + BehaviorSubject.createDefault(messageRepo.getUnreadMessages(threadId)) init { disposables += markRead @@ -65,10 +69,11 @@ class QkReplyViewModel @Inject constructor( // When the set of messages changes, update the state // If we're ever showing an empty set of messages, then it's time to shut down to activity - disposables += messages - .withLatestFrom(conversation, { messages, conversation -> Pair(conversation, messages) }) - .doOnNext { data -> newState { it.copy(data = data) } } - .map { data -> data.second } + disposables += Observables + .combineLatest(messages, conversation) { messages, conversation -> + newState { it.copy(data = Pair(conversation, messages)) } + messages + } .switchMap { messages -> messages.asObservable() } .filter { it.isLoaded } .filter { it.isValid } @@ -76,10 +81,18 @@ class QkReplyViewModel @Inject constructor( .subscribe { newState { it.copy(hasError = true) } } disposables += conversation - .doOnNext { conversation -> newState { it.copy(title = conversation.getTitle()) } } - .distinctUntilChanged { conversation -> conversation.id } // We only need to set the messages once - .map { conversation -> messageRepo.getUnreadMessages(conversation.id) } - .subscribe { messages.onNext(it) } + .map { conversation -> conversation.getTitle() } + .distinctUntilChanged() + .subscribe { title -> newState { it.copy(title = title) } } + + val latestSubId = messages + .map { messages -> messages.lastOrNull()?.subId ?: -1 } + .distinctUntilChanged() + + disposables += Observables.combineLatest(latestSubId, subUtils.subscriptionsObservable) { subId, subs -> + val sub = if (subs.size > 1) subs.firstOrNull { it.subscriptionId == subId } ?: subs[0] else null + newState { it.copy(subscription = sub) } + }.subscribe() } override fun bindView(view: QkReplyView) { @@ -115,7 +128,7 @@ class QkReplyViewModel @Inject constructor( .filter { id -> id == R.id.expand } .withLatestFrom(conversation, { _, conversation -> conversation }) .map { conversation -> messageRepo.getMessages(conversation.id) } - .doOnNext { messages.onNext(it) } + .doOnNext(messages::onNext) .autoDisposable(view.scope()) .subscribe { newState { it.copy(expanded = true) } } @@ -124,7 +137,7 @@ class QkReplyViewModel @Inject constructor( .filter { id -> id == R.id.collapse } .withLatestFrom(conversation, { _, conversation -> conversation }) .map { conversation -> messageRepo.getUnreadMessages(conversation.id) } - .doOnNext { messages.onNext(it) } + .doOnNext(messages::onNext) .autoDisposable(view.scope()) .subscribe { newState { it.copy(expanded = false) } } @@ -173,18 +186,31 @@ class QkReplyViewModel @Inject constructor( .autoDisposable(view.scope()) .subscribe() + // Toggle to the next sim slot + view.changeSimIntent + .withLatestFrom(state) { _, state -> + val subs = subUtils.subscriptions + val subIndex = subs.indexOfFirst { it.subscriptionId == state.subscription?.subscriptionId } + val subscription = when { + subIndex == -1 -> null + subIndex < subs.size - 1 -> subs[subIndex + 1] + else -> subs[0] + } + newState { it.copy(subscription = subscription) } + } + .autoDisposable(view.scope()) + .subscribe() + // Send a message when the send button is clicked, and disable editing mode if it's enabled view.sendIntent .withLatestFrom(view.textChangedIntent, { _, body -> body }) .map { body -> body.toString() } - .withLatestFrom(conversation, { body, conversation -> + .withLatestFrom(state, conversation, { body, state, conversation -> + val subId = state.subscription?.subscriptionId ?: -1 val threadId = conversation.id val addresses = conversation.recipients.map { it.address } - + sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body)) view.setDraft("") - sendMessage.execute(SendMessage.Params(threadId, addresses, body, listOf())) { - } - threadId }) .doOnNext { threadId -> diff --git a/presentation/src/main/java/injection/AppModule.kt b/presentation/src/main/java/injection/AppModule.kt index 1efb8016..4ac2bcca 100644 --- a/presentation/src/main/java/injection/AppModule.kt +++ b/presentation/src/main/java/injection/AppModule.kt @@ -59,6 +59,8 @@ import repository.MessageRepository import repository.MessageRepositoryImpl import repository.SyncRepository import repository.SyncRepositoryImpl +import util.SubscriptionUtils +import util.SubscriptionUtilsImpl import javax.inject.Singleton @Module @@ -137,4 +139,10 @@ class AppModule(private var application: Application) { @Provides fun provideSyncRepository(repository: SyncRepositoryImpl): SyncRepository = repository + + // Utils + + @Provides + fun provideSubscriptionUtils(utils: SubscriptionUtilsImpl): SubscriptionUtils = utils + } \ No newline at end of file diff --git a/presentation/src/main/res/drawable/ic_sim_card_black_24dp.xml b/presentation/src/main/res/drawable/ic_sim_card_black_24dp.xml new file mode 100644 index 00000000..071707fe --- /dev/null +++ b/presentation/src/main/res/drawable/ic_sim_card_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/presentation/src/main/res/layout/compose_activity.xml b/presentation/src/main/res/layout/compose_activity.xml index d8ceaa78..318f46de 100644 --- a/presentation/src/main/res/layout/compose_activity.xml +++ b/presentation/src/main/res/layout/compose_activity.xml @@ -1,4 +1,5 @@ - + + + app:layout_constraintBottom_toBottomOf="@id/messageBackground" + app:layout_constraintEnd_toStartOf="@id/sim" + app:layout_constraintStart_toStartOf="@id/messageBackground" /> + + + +