#207 - Dual SIM support

commit c3dc3ada558c466be5115cd7ddbf9651a229c217
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Sat Jun 2 02:54:06 2018 -0400

    Dual SIM support for QK Reply

commit 48688dd4720bd1b3abc049d365e208e1dfe5ccb8
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Sat Jun 2 00:37:08 2018 -0400

    #1172 - Load all recipients and subId from threadId when sending message from notification reply bar

commit 0b7195fb134c0a9f2a6b551176c6c25a26bf5838
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 23:43:30 2018 -0400

    Fix missing subId for RetrySending params

commit 0d3ec43c0e60bab4acc293947ea9f6d2228c1b19
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 23:27:56 2018 -0400

    Switch to appropriate SIM when new message is received

commit 1ae883af890104cf1da9e970571371c95666db66
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 23:07:16 2018 -0400

    Fix message grouping for incoming messages

commit 2bf7b2d99ddbfdcafff873f305180d6d38c37d65
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 22:56:31 2018 -0400

    Correctly assign subId for incoming SMS

commit 1f6028f8921320358a3053a2dbc2c6e05410964b
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 20:52:01 2018 -0400

    Abstract SubscriptionManager usage behind SubscriptionUtils

commit 8b18f16271f19a42800c737cfbd867365c4aa781
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 20:05:52 2018 -0400

    Store subId when receiving SMS

commit f0e4ffdf15eb54d8ef78adfe244943ef4cb95d4e
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Fri Jun 1 19:52:40 2018 -0400

    Use appropriate SIM card based on last message

commit b7893d69891e4fb61755b0733a5fab561e86bbf3
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Thu May 31 00:20:42 2018 -0400

    Fix crash when device doesn't support multi-sim

commit bb038068129227e931167976628e1a535efb09a0
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Wed May 30 23:54:14 2018 -0400

    Show sim indicator when subId changes in conversation

commit 952f15f7ebfb85a03feef51373ef30568b76d5eb
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Wed May 30 22:13:57 2018 -0400

    Send message from selected SIM

commit 4cfab7ca9ec9bd9c7ce82b3eb5f228cf511a7c7b
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Wed May 30 21:46:01 2018 -0400

    Fix filename for ActiveSubscriptionObservable

commit 720cb79cb4fbfb98b10e169f2fea84be02fd2f91
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Wed May 30 20:35:30 2018 -0400

    Allow cycling through inserted sims

commit fa95980e9bc8e8c01dab7b4b8e4ed3a1c9a0f0b0
Author: Moez Bhatti <moez.bhatti@gmail.com>
Date:   Wed May 30 18:26:44 2018 -0400

    Show sim card slot in compose bar
This commit is contained in:
Moez Bhatti
2018-06-02 02:58:42 -04:00
parent f71d2564b2
commit 1f345da920
32 changed files with 424 additions and 116 deletions
@@ -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)
@@ -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) {
@@ -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" -> {
@@ -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() }
}
}
+3 -1
View File
@@ -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() })
}
}
@@ -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<String>, body: String, attachments: List<Attachment>) {
val settings = Settings()
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
@@ -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)
@@ -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))
}
}
@@ -0,0 +1,59 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* 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 <http://www.gnu.org/licenses/>.
*/
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<List<SubscriptionInfo>>() {
override fun subscribeActual(observer: Observer<in List<SubscriptionInfo>>) {
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<in List<SubscriptionInfo>>
) : 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)
}
}
}
@@ -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<SubscriptionInfo>
get() = subscriptionManager.activeSubscriptionInfoList ?: listOf()
override val subscriptionsObservable: Observable<List<SubscriptionInfo>> = ActiveSubscriptionObservable(subscriptionManager)
override fun getSubIdForAddress(address: String): Int {
return subscriptions.firstOrNull { PhoneNumberUtils.compare(it.number, address) }?.subscriptionId ?: -1
}
}
+10 -7
View File
@@ -32,23 +32,26 @@ class ReceiveSms @Inject constructor(
private val messageRepo: MessageRepository,
private val notificationManager: NotificationManager,
private val updateBadge: UpdateBadge
) : Interactor<Array<SmsMessage>>() {
) : Interactor<ReceiveSms.Params>() {
override fun buildObservable(params: Array<SmsMessage>): Flowable<*> {
class Params(val subId: Int, val messages: Array<SmsMessage>)
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
@@ -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)
@@ -27,16 +27,16 @@ class SendMessage @Inject constructor(
private val messageRepo: MessageRepository
) : Interactor<SendMessage.Params>() {
data class Params(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())
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.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) }
+4 -2
View File
@@ -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
}
}
@@ -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<String>, body: String, attachments: List<Attachment>)
fun sendMms(subId: Int, threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>)
/**
* 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
@@ -0,0 +1,14 @@
package util
import android.telephony.SubscriptionInfo
import io.reactivex.Observable
interface SubscriptionUtils {
val subscriptions: List<SubscriptionInfo>
val subscriptionsObservable: Observable<List<SubscriptionInfo>>
fun getSubIdForAddress(address: String): Int
}
@@ -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)
@@ -89,12 +89,13 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
override val galleryIntent by lazy { gallery.clicks() }
override val attachmentSelectedIntent: Subject<Uri> = 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<Unit> = 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
}
@@ -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<Attachment> = ArrayList(),
val attaching: Boolean = false,
val remaining: String = "",
val subscription: SubscriptionInfo? = null,
val canSend: Boolean = false
)
@@ -47,6 +47,7 @@ interface ComposeView : QkView<ComposeState> {
val galleryIntent: Observable<*>
val attachmentSelectedIntent: Observable<Uri>
val inputContentIntent: Observable<InputContentInfoCompat>
val changeSimIntent: Observable<*>
val sendIntent: Observable<Unit>
fun clearSelection()
@@ -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<ComposeView, ComposeState>(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())
})
@@ -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<Message>() {
companion object {
@@ -116,6 +116,7 @@ class MessagesAdapter @Inject constructor(
private val contactCache = ContactCache()
private val expanded = HashMap<Long, Boolean>()
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?) {
@@ -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<Int> = 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
}
@@ -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
@@ -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<Conversation, RealmResults<Message>>? = null,
val remaining: String = "",
val subscription: SubscriptionInfo? = null,
val canSend: Boolean = false
)
@@ -25,6 +25,7 @@ interface QkReplyView : QkView<QkReplyState> {
val menuItemIntent: Observable<Int>
val textChangedIntent: Observable<CharSequence>
val changeSimIntent: Observable<*>
val sendIntent: Observable<Unit>
fun setDraft(draft: String)
@@ -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<QkReplyView, QkReplyState>(QkReplyState()) {
private val conversation by lazy {
messageRepo.getConversationAsync(intent.getLongExtra("threadId", -1))
messageRepo.getConversationAsync(threadId)
.asObservable<Conversation>()
.filter { it.isLoaded }
.filter { it.isValid }
.distinctUntilChanged()
}
private val messages: Subject<RealmResults<Message>> = PublishSubject.create()
private val messages: Subject<RealmResults<Message>> =
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 ->
@@ -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
}
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M18,2h-8L4.02,8 4,20c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L20,4c0,-1.1 -0.9,-2 -2,-2zM14,8h"/>
</vector>
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?><!--
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
~
~ This file is part of QKSMS.
@@ -184,9 +185,37 @@
android:padding="12dp"
android:textColorHint="?android:attr/textColorTertiary"
app:layout_constraintBottom_toBottomOf="@id/messageBackground"
app:layout_constraintEnd_toEndOf="@id/messageBackground"
app:layout_constraintEnd_toStartOf="@id/sim"
app:layout_constraintStart_toEndOf="@id/attachSeparator" />
<ImageView
android:id="@+id/sim"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginEnd="8dp"
android:background="?attr/selectableItemBackground"
android:contentDescription="@string/compose_attach_cd"
android:padding="10dp"
android:src="@drawable/ic_sim_card_black_24dp"
android:tint="?android:attr/textColorSecondary"
app:layout_constraintBottom_toBottomOf="@id/message"
app:layout_constraintEnd_toEndOf="@id/messageBackground" />
<common.widget.QkTextView
android:id="@+id/simIndex"
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textSize="14dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@id/sim"
app:layout_constraintEnd_toEndOf="@id/sim"
app:layout_constraintStart_toStartOf="@id/sim"
app:layout_constraintTop_toTopOf="@id/sim"
tools:ignore="SpUsage"
tools:text="1" />
<common.widget.QkTextView
android:id="@+id/counter"
android:layout_width="0dp"
@@ -31,11 +31,36 @@
android:layout_height="wrap_content"
android:gravity="center"
android:padding="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintEnd_toStartOf="@id/sim"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Tue at 11:39pm" />
<ImageView
android:id="@+id/sim"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginEnd="2dp"
android:src="@drawable/ic_sim_card_black_24dp"
android:tint="?android:attr/textColorSecondary"
app:layout_constraintBottom_toBottomOf="@id/timestamp"
app:layout_constraintEnd_toStartOf="@id/simIndex"
app:layout_constraintStart_toEndOf="@id/timestamp"
app:layout_constraintTop_toTopOf="@id/timestamp" />
<common.widget.QkTextView
android:id="@+id/simIndex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorSecondary"
app:layout_constraintBottom_toBottomOf="@id/timestamp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/sim"
app:layout_constraintTop_toTopOf="@id/timestamp"
app:textSize="tertiary"
tools:text="1" />
<LinearLayout
android:id="@+id/attachments"
android:layout_width="wrap_content"
@@ -31,11 +31,36 @@
android:layout_height="wrap_content"
android:gravity="center"
android:padding="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintEnd_toStartOf="@id/sim"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Tue at 11:39pm" />
<ImageView
android:id="@+id/sim"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginEnd="2dp"
android:src="@drawable/ic_sim_card_black_24dp"
android:tint="?android:attr/textColorSecondary"
app:layout_constraintBottom_toBottomOf="@id/timestamp"
app:layout_constraintEnd_toStartOf="@id/simIndex"
app:layout_constraintStart_toEndOf="@id/timestamp"
app:layout_constraintTop_toTopOf="@id/timestamp" />
<common.widget.QkTextView
android:id="@+id/simIndex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorSecondary"
app:layout_constraintBottom_toBottomOf="@id/timestamp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/sim"
app:layout_constraintTop_toTopOf="@id/timestamp"
app:textSize="tertiary"
tools:text="1" />
<LinearLayout
android:id="@+id/attachments"
android:layout_width="wrap_content"
@@ -69,27 +69,79 @@
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/composeBackgroundGradient" />
<View
android:id="@+id/messageBackground"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@drawable/rounded_rectangle_shadow"
android:backgroundTint="?attr/bubbleColor"
android:backgroundTintMode="multiply"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/send"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/messagePadding" />
<!-- The padding inside the messageBackground view is broken, probably because of 9patch weirdness -->
<View
android:id="@+id/messagePadding"
android:layout_width="0dp"
android:layout_height="8dp"
android:paddingEnd="8dp"
android:paddingStart="8dp"
android:paddingTop="8dp"
app:layout_constraintBottom_toTopOf="@id/message"
app:layout_constraintEnd_toEndOf="@id/messageBackground"
app:layout_constraintStart_toStartOf="@id/messageBackground"
app:layout_constraintTop_toTopOf="@id/messageBackground" />
<common.widget.QkEditText
android:id="@+id/message"
style="@style/TextPrimary"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:background="@drawable/rounded_rectangle_shadow"
android:backgroundTint="?attr/bubbleColor"
android:backgroundTintMode="multiply"
android:background="@null"
android:gravity="center_vertical"
android:hint="@string/compose_hint"
android:inputType="textLongMessage|textCapSentences|textMultiLine"
android:maxLines="6"
android:minHeight="44dp"
android:padding="20dp"
android:padding="12dp"
android:textColorHint="?android:attr/textColorTertiary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/messageBackground"
app:layout_constraintEnd_toStartOf="@id/send"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/messages" />
app:layout_constraintBottom_toBottomOf="@id/messageBackground"
app:layout_constraintEnd_toStartOf="@id/sim"
app:layout_constraintStart_toStartOf="@id/messageBackground" />
<ImageView
android:id="@+id/sim"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginEnd="8dp"
android:background="?attr/selectableItemBackground"
android:contentDescription="@string/compose_attach_cd"
android:padding="10dp"
android:src="@drawable/ic_sim_card_black_24dp"
android:tint="?android:attr/textColorSecondary"
app:layout_constraintBottom_toBottomOf="@id/message"
app:layout_constraintEnd_toEndOf="@id/messageBackground" />
<common.widget.QkTextView
android:id="@+id/simIndex"
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textSize="14dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@id/sim"
app:layout_constraintEnd_toEndOf="@id/sim"
app:layout_constraintStart_toStartOf="@id/sim"
app:layout_constraintTop_toTopOf="@id/sim"
tools:ignore="SpUsage"
tools:text="1" />
<common.widget.QkTextView
android:id="@+id/counter"