mirror of
https://github.com/quik-sms/quik.git
synced 2026-11-18 03:48:52 +01:00
Fix case where Conversation isn't returned and can't send message
This commit is contained in:
@@ -37,9 +37,13 @@ object TelephonyCompat {
|
||||
|
||||
val NAME_ADDR_EMAIL_PATTERN = Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*")
|
||||
|
||||
fun getOrCreateThreadId(context: Context, recipients: Set<String>): Long {
|
||||
fun getOrCreateThreadId(context: Context, recipient: String): Long {
|
||||
return getOrCreateThreadId(context, listOf(recipient))
|
||||
}
|
||||
|
||||
fun getOrCreateThreadId(context: Context, recipients: Collection<String>): Long {
|
||||
return if (Build.VERSION.SDK_INT >= 23) {
|
||||
Telephony.Threads.getOrCreateThreadId(context, recipients)
|
||||
Telephony.Threads.getOrCreateThreadId(context, recipients.toSet())
|
||||
} else {
|
||||
val uriBuilder = THREAD_ID_CONTENT_URI.buildUpon()
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ import compat.TelephonyCompat
|
||||
import filter.ConversationFilter
|
||||
import io.realm.Case
|
||||
import io.realm.Realm
|
||||
import io.realm.RealmList
|
||||
import io.realm.RealmResults
|
||||
import io.realm.Sort
|
||||
import manager.KeyManager
|
||||
@@ -48,10 +49,13 @@ import model.Contact
|
||||
import model.Conversation
|
||||
import model.Message
|
||||
import model.MmsPart
|
||||
import model.Recipient
|
||||
import model.SearchResult
|
||||
import timber.log.Timber
|
||||
import util.Preferences
|
||||
import util.extensions.anyOf
|
||||
import util.extensions.forEach
|
||||
import util.extensions.insertOrUpdate
|
||||
import util.extensions.map
|
||||
import util.tryOrNull
|
||||
import java.io.ByteArrayOutputStream
|
||||
@@ -551,6 +555,9 @@ class MessageRepositoryImpl @Inject constructor(
|
||||
|
||||
// Update the contentId after the message has been inserted to the content provider
|
||||
// The message might have been deleted by now, so only proceed if it's valid
|
||||
//
|
||||
// We do this after inserting the message because it might be slow, and we want the message
|
||||
// to be inserted into Realm immediately. We don't need to do this after receiving one
|
||||
realm.executeTransaction { managedMessage?.takeIf { it.isValid }?.contentId = uri.lastPathSegment.toLong() }
|
||||
realm.close()
|
||||
|
||||
@@ -559,23 +566,6 @@ class MessageRepositoryImpl @Inject constructor(
|
||||
|
||||
override fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long): Message {
|
||||
|
||||
// Insert the message to Realm
|
||||
val message = Message().apply {
|
||||
this.address = address
|
||||
this.body = body
|
||||
this.dateSent = sentTime
|
||||
this.date = System.currentTimeMillis()
|
||||
this.subId = subId
|
||||
|
||||
id = messageIds.newId()
|
||||
threadId = getOrCreateConversation(address)?.id ?: 0L
|
||||
boxId = Telephony.Sms.MESSAGE_TYPE_INBOX
|
||||
type = "sms"
|
||||
}
|
||||
val realm = Realm.getDefaultInstance()
|
||||
var managedMessage: Message? = null
|
||||
realm.executeTransaction { managedMessage = realm.copyToRealmOrUpdate(message) }
|
||||
|
||||
// Insert the message to the native content provider
|
||||
val values = ContentValues().apply {
|
||||
put(Telephony.Sms.ADDRESS, address)
|
||||
@@ -585,11 +575,21 @@ class MessageRepositoryImpl @Inject constructor(
|
||||
}
|
||||
val uri = context.contentResolver.insert(Telephony.Sms.Inbox.CONTENT_URI, values)
|
||||
|
||||
// Update the contentId after the message has been inserted to the content provider
|
||||
realm.executeTransaction { managedMessage?.contentId = uri.lastPathSegment.toLong() }
|
||||
realm.close()
|
||||
// Insert the message to Realm
|
||||
return Message().apply {
|
||||
this.address = address
|
||||
this.body = body
|
||||
this.dateSent = sentTime
|
||||
this.date = System.currentTimeMillis()
|
||||
this.subId = subId
|
||||
|
||||
return message
|
||||
id = messageIds.newId()
|
||||
threadId = getOrCreateConversation(address)?.id ?: 0L
|
||||
contentId = uri.lastPathSegment.toLong()
|
||||
boxId = Telephony.Sms.MESSAGE_TYPE_INBOX
|
||||
type = "sms"
|
||||
insertOrUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -735,6 +735,13 @@ class MessageRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a [Conversation] from the system SMS ContentProvider, based on the [threadId]
|
||||
*
|
||||
* It should be noted that even if we have a valid [threadId], that does not guarantee that
|
||||
* we can return a [Conversation]. On some devices, the ContentProvider won't return the
|
||||
* conversation unless it contains at least 1 message
|
||||
*/
|
||||
private fun getConversationFromCp(threadId: Long): Conversation? {
|
||||
return cursorToConversation.getConversationCursor(threadId)
|
||||
?.takeIf { cursor -> cursor.moveToFirst() }
|
||||
|
||||
@@ -38,7 +38,7 @@ fun <T : RealmModel> Collection<T>.insertOrUpdate() {
|
||||
realm.close()
|
||||
}
|
||||
|
||||
fun <T : RealmObject> RealmObject.asObservable(): Observable<T> {
|
||||
fun <T : RealmObject> T.asObservable(): Observable<T> {
|
||||
return asFlowable<T>().toObservable()
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@ class SendMessage @Inject constructor(
|
||||
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 { messageRepo.getOrCreateConversation(params.threadId) }
|
||||
.doOnNext { messageRepo.updateConversations(params.threadId) }
|
||||
.doOnNext { messageRepo.markUnarchived(params.threadId) }
|
||||
}
|
||||
|
||||
@@ -23,23 +23,24 @@ import io.realm.RealmObject
|
||||
import io.realm.annotations.Index
|
||||
import io.realm.annotations.PrimaryKey
|
||||
|
||||
open class Conversation : RealmObject() {
|
||||
open class Conversation(
|
||||
@PrimaryKey var id: Long = 0,
|
||||
@Index var archived: Boolean = false,
|
||||
@Index var blocked: Boolean = false,
|
||||
var recipients: RealmList<Recipient> = RealmList(),
|
||||
var count: Int = 0,
|
||||
var date: Long = 0,
|
||||
var snippet: String = "",
|
||||
var read: Boolean = true,
|
||||
var me: Boolean = false,
|
||||
var draft: String = "",
|
||||
|
||||
@PrimaryKey var id: Long = 0
|
||||
@Index var archived: Boolean = false
|
||||
@Index var blocked: Boolean = false
|
||||
var recipients: RealmList<Recipient> = RealmList()
|
||||
var count: Int = 0
|
||||
var date: Long = 0
|
||||
var snippet: String = ""
|
||||
var read: Boolean = true
|
||||
var me: Boolean = false
|
||||
var draft: String = ""
|
||||
|
||||
// For group chats, the user is allowed to set a custom title for the conversation
|
||||
var name: String = ""
|
||||
// For group chats, the user is allowed to set a custom title for the conversation
|
||||
var name: String = ""
|
||||
) : RealmObject() {
|
||||
|
||||
fun getTitle(): String {
|
||||
return name.takeIf { it.isNotBlank() } ?: recipients.joinToString { recipient -> recipient.getDisplayName() }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,12 +23,12 @@ import io.realm.RealmObject
|
||||
import io.realm.annotations.PrimaryKey
|
||||
import java.util.*
|
||||
|
||||
open class Recipient : RealmObject() {
|
||||
|
||||
@PrimaryKey var id: Long = 0
|
||||
var address: String = ""
|
||||
var contact: Contact? = null
|
||||
var lastUpdate: Long = 0
|
||||
open class Recipient(
|
||||
@PrimaryKey var id: Long = 0,
|
||||
var address: String = "",
|
||||
var contact: Contact? = null,
|
||||
var lastUpdate: Long = 0
|
||||
) : RealmObject() {
|
||||
|
||||
/**
|
||||
* Return a string that can be displayed to represent the name of this contact
|
||||
|
||||
@@ -2,16 +2,62 @@ package feature.compose
|
||||
|
||||
import android.arch.lifecycle.ViewModel
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.multibindings.IntoMap
|
||||
import injection.ViewModelKey
|
||||
import model.Attachment
|
||||
import java.net.URLDecoder
|
||||
import javax.inject.Named
|
||||
|
||||
@Module
|
||||
class ComposeActivityModule {
|
||||
|
||||
@Provides
|
||||
fun provideIntent(activity: ComposeActivity): Intent = activity.intent
|
||||
@Named("query")
|
||||
fun provideQuery(activity: ComposeActivity): String = activity.intent.extras?.getString("query") ?: ""
|
||||
|
||||
@Provides
|
||||
@Named("threadId")
|
||||
fun provideThreadId(activity: ComposeActivity): Long = activity.intent.extras?.getLong("threadId") ?: 0L
|
||||
|
||||
@Provides
|
||||
@Named("address")
|
||||
fun provideAddress(activity: ComposeActivity): String {
|
||||
var address = ""
|
||||
|
||||
activity.intent.data?.let {
|
||||
val data = it.toString()
|
||||
address = when {
|
||||
it.scheme.startsWith("smsto") -> data.replace("smsto:", "")
|
||||
it.scheme.startsWith("mmsto") -> data.replace("mmsto:", "")
|
||||
it.scheme.startsWith("sms") -> data.replace("sms:", "")
|
||||
it.scheme.startsWith("mms") -> data.replace("mms:", "")
|
||||
else -> ""
|
||||
}
|
||||
|
||||
// The dialer app on Oreo sends a URL encoded string, make sure to decode it
|
||||
if (address.contains('%')) address = URLDecoder.decode(address, "UTF-8")
|
||||
}
|
||||
|
||||
return address
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Named("text")
|
||||
fun provideSharedText(activity: ComposeActivity): String {
|
||||
return activity.intent.extras?.getString(Intent.EXTRA_TEXT) ?: ""
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Named("attachments")
|
||||
fun provideSharedAttachments(activity: ComposeActivity): List<Attachment> {
|
||||
val sharedImages = mutableListOf<Uri>()
|
||||
activity.intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run(sharedImages::add)
|
||||
activity.intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run(sharedImages::addAll)
|
||||
return sharedImages.map { Attachment(it) }
|
||||
}
|
||||
|
||||
@Provides
|
||||
@IntoMap
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
*/
|
||||
package feature.compose
|
||||
|
||||
import android.telephony.SubscriptionInfo
|
||||
import compat.SubscriptionInfoCompat
|
||||
import io.realm.RealmResults
|
||||
import model.Attachment
|
||||
|
||||
@@ -19,8 +19,6 @@
|
||||
package feature.compose
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.telephony.PhoneNumberUtils
|
||||
import android.telephony.SmsMessage
|
||||
import android.view.inputmethod.EditorInfo
|
||||
@@ -32,6 +30,7 @@ import common.base.QkViewModel
|
||||
import common.util.ClipboardUtils
|
||||
import common.util.extensions.makeToast
|
||||
import compat.SubscriptionManagerCompat
|
||||
import compat.TelephonyCompat
|
||||
import filter.ContactFilter
|
||||
import interactor.CancelDelayedMessage
|
||||
import interactor.ContactSync
|
||||
@@ -55,6 +54,7 @@ import model.Contact
|
||||
import model.Conversation
|
||||
import model.Message
|
||||
import model.PhoneNumber
|
||||
import model.Recipient
|
||||
import repository.ContactRepository
|
||||
import repository.MessageRepository
|
||||
import util.ActiveSubscriptionObservable
|
||||
@@ -63,13 +63,17 @@ import util.extensions.isImage
|
||||
import util.extensions.mapNotNull
|
||||
import util.extensions.removeAccents
|
||||
import util.tryOrNull
|
||||
import java.net.URLDecoder
|
||||
import java.util.*
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Named
|
||||
|
||||
class ComposeViewModel @Inject constructor(
|
||||
private val intent: Intent,
|
||||
@Named("query") private val query: String,
|
||||
@Named("threadId") private val threadId: Long,
|
||||
@Named("address") private val address: String,
|
||||
@Named("text") private val sharedText: String,
|
||||
@Named("attachments") private val sharedAttachments: List<Attachment>,
|
||||
private val context: Context,
|
||||
private val cancelMessage: CancelDelayedMessage,
|
||||
private val contactFilter: ContactFilter,
|
||||
@@ -83,81 +87,45 @@ class ComposeViewModel @Inject constructor(
|
||||
private val sendMessage: SendMessage,
|
||||
private val subscriptionManager: SubscriptionManagerCompat,
|
||||
private val syncContacts: ContactSync
|
||||
) : QkViewModel<ComposeView, ComposeState>(ComposeState(query = intent.extras?.getString("query") ?: "")) {
|
||||
) : QkViewModel<ComposeView, ComposeState>(ComposeState(
|
||||
editingMode = threadId == 0L,
|
||||
selectedConversation = threadId,
|
||||
query = query)
|
||||
) {
|
||||
|
||||
private var sharedText: String = intent.extras?.getString(Intent.EXTRA_TEXT) ?: ""
|
||||
private val attachments: Subject<List<Attachment>> = BehaviorSubject.createDefault(ArrayList())
|
||||
private val attachments: Subject<List<Attachment>> = BehaviorSubject.createDefault(sharedAttachments)
|
||||
private val contacts: Observable<List<Contact>> by lazy { contactsRepo.getUnmanagedContacts().toObservable() }
|
||||
private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create()
|
||||
private val selectedContacts: Observable<List<Contact>>
|
||||
private val selectedContacts: Subject<List<Contact>> = BehaviorSubject.create()
|
||||
private val searchResults: Subject<List<Message>> = BehaviorSubject.create()
|
||||
private val searchSelection: Subject<Long> = BehaviorSubject.createDefault(-1)
|
||||
private val conversation: Subject<Conversation> = BehaviorSubject.create()
|
||||
private val messages: Subject<List<Message>> = BehaviorSubject.create()
|
||||
|
||||
init {
|
||||
// If there are any image attachments, we'll set those as the initial attachments for the
|
||||
// conversation
|
||||
val sharedImages = mutableListOf<Uri>()
|
||||
intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
|
||||
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
|
||||
attachments.onNext(sharedImages.map { uri -> Attachment(uri) })
|
||||
|
||||
val threadId = intent.extras?.getLong("threadId") ?: 0L
|
||||
var address = ""
|
||||
|
||||
intent.data?.let {
|
||||
val data = it.toString()
|
||||
address = when {
|
||||
it.scheme.startsWith("smsto") -> data.replace("smsto:", "")
|
||||
it.scheme.startsWith("mmsto") -> data.replace("mmsto:", "")
|
||||
it.scheme.startsWith("sms") -> data.replace("sms:", "")
|
||||
it.scheme.startsWith("mms") -> data.replace("mms:", "")
|
||||
else -> ""
|
||||
}
|
||||
|
||||
// The dialer app on Oreo sends a URL encoded string, make sure to decode it
|
||||
if (address.contains('%')) address = URLDecoder.decode(address, "UTF-8")
|
||||
}
|
||||
|
||||
val initialConversation: Observable<Conversation> = when {
|
||||
threadId != 0L -> {
|
||||
newState { copy(selectedConversation = threadId, editingMode = false) }
|
||||
messageRepo.getConversationAsync(threadId).asObservable()
|
||||
}
|
||||
|
||||
address.isNotBlank() -> {
|
||||
newState { copy(editingMode = false) }
|
||||
Observable.just(address)
|
||||
.mapNotNull { messageRepo.getOrCreateConversation(it) }
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
}
|
||||
|
||||
else -> {
|
||||
newState { copy(editingMode = true) }
|
||||
Observable.empty()
|
||||
}
|
||||
}
|
||||
|
||||
selectedContacts = contactsReducer
|
||||
.scan(listOf<Contact>(), { previousState, reducer -> reducer(previousState) })
|
||||
.doOnNext { contacts -> newState { copy(selectedContacts = contacts) } }
|
||||
val initialConversation = threadId.takeIf { it != 0L }
|
||||
?.let(messageRepo::getConversationAsync)
|
||||
?.asObservable()
|
||||
?: Observable.empty()
|
||||
|
||||
// Merges two potential conversation sources (threadId from constructor and contact selection) into a single
|
||||
// stream of conversations. If the conversation was deleted, notify the activity to shut down
|
||||
disposables += selectedContacts
|
||||
.skipUntil(state.filter { state -> state.editingMode })
|
||||
.takeUntil(state.filter { state -> !state.editingMode })
|
||||
.skipWhile { it.isEmpty() }
|
||||
.map { contacts -> contacts.map { it.numbers.firstOrNull()?.address ?: "" } }
|
||||
.observeOn(Schedulers.computation())
|
||||
.doOnNext { newState { copy(loading = true) } }
|
||||
.mapNotNull { addresses ->
|
||||
val conversation = messageRepo.getOrCreateConversation(addresses)
|
||||
newState { copy(loading = false) }
|
||||
conversation
|
||||
}
|
||||
.observeOn(Schedulers.computation())
|
||||
.map { addresses -> Pair(TelephonyCompat.getOrCreateThreadId(context, addresses), addresses) }
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.doOnNext { newState { copy(loading = false) } }
|
||||
.switchMap { (threadId, addresses) ->
|
||||
val recipients = RealmList(*addresses.map { address -> Recipient(address = address) }.toTypedArray())
|
||||
messageRepo.getConversations().asObservable()
|
||||
.map { conversations -> conversations.filter { it.id == threadId } }
|
||||
.map { conversations ->
|
||||
conversations.firstOrNull() ?: Conversation(id = threadId, recipients = recipients)
|
||||
}
|
||||
}
|
||||
.mergeWith(initialConversation)
|
||||
.filter { conversation -> conversation.isLoaded }
|
||||
.doOnNext { conversation ->
|
||||
@@ -166,9 +134,19 @@ class ComposeViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
.filter { conversation -> conversation.isValid }
|
||||
.filter { conversation -> conversation.id != 0L }
|
||||
.subscribe(conversation::onNext)
|
||||
|
||||
if (address.isNotBlank()) {
|
||||
selectedContacts.onNext(listOf(Contact(numbers = RealmList(PhoneNumber(address)))))
|
||||
}
|
||||
|
||||
disposables += contactsReducer
|
||||
.scan(listOf<Contact>(), { previousState, reducer -> reducer(previousState) })
|
||||
.doOnNext { contacts -> newState { copy(selectedContacts = contacts) } }
|
||||
.skipUntil(state.filter { state -> state.editingMode })
|
||||
.takeUntil(state.filter { state -> !state.editingMode })
|
||||
.subscribe(selectedContacts::onNext)
|
||||
|
||||
// When the conversation changes, update the threadId and the messages for the adapter
|
||||
disposables += conversation
|
||||
.distinctUntilChanged { conversation -> conversation.id }
|
||||
@@ -553,11 +531,11 @@ class ComposeViewModel @Inject constructor(
|
||||
.map { contact -> contact.numbers }
|
||||
.mapNotNull { numbers -> numbers.firstOrNull() }
|
||||
.map { number -> number.address }
|
||||
.mapNotNull { address -> messageRepo.getOrCreateConversation(address) }
|
||||
.filter { it.recipients.isNotEmpty() }
|
||||
.forEach {
|
||||
val address = it.recipients.map { it.address }
|
||||
sendMessage.execute(SendMessage.Params(subId, it.id, address, body, attachments))
|
||||
.forEach { addr ->
|
||||
val threadId = TelephonyCompat.getOrCreateThreadId(context, addr)
|
||||
val address = listOf(messageRepo.getConversation(threadId)?.recipients?.firstOrNull()?.address
|
||||
?: addr)
|
||||
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, attachments))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user