Sync contacts during partial sync

This commit is contained in:
Moez Bhatti
2017-12-14 20:18:16 -05:00
parent ebe469851e
commit 5213998c9c
15 changed files with 69 additions and 53 deletions
@@ -3,9 +3,10 @@ package com.moez.QKSMS.data.mapper
import android.database.Cursor
import android.net.Uri
import com.moez.QKSMS.data.model.Recipient
import com.moez.QKSMS.data.repository.ContactRepository
import javax.inject.Inject
class CursorToRecipient @Inject constructor() : Mapper<Cursor, Recipient> {
class CursorToRecipient @Inject constructor(private val contactRepository: ContactRepository) : Mapper<Cursor, Recipient> {
companion object {
val URI = Uri.parse("content://mms-sms/canonical-addresses")
@@ -17,6 +18,8 @@ class CursorToRecipient @Inject constructor() : Mapper<Cursor, Recipient> {
override fun map(from: Cursor) = Recipient().apply {
id = from.getLong(COLUMN_ID)
address = from.getString(COLUMN_ADDRESS)
contact = contactRepository.getContactBlocking(address) // TODO do this lazily for faster syncs
lastUpdate = System.currentTimeMillis()
}
}
@@ -1,15 +1,13 @@
package com.moez.QKSMS.data.model
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Contact() : RealmObject() {
open class Contact : RealmObject() {
@PrimaryKey var recipientId: Long = 0
var lookupKey: String = ""
var address: String = ""
var numbers: RealmList<PhoneNumber> = RealmList()
var name: String = ""
var inContactsTable: Boolean = false
var lastUpdate: Long = 0
}
@@ -13,7 +13,7 @@ open class Conversation : RealmObject() {
fun getTitle(): String {
var title = ""
recipients.forEachIndexed { index, recipient ->
title += recipient.address
title += recipient.contact?.name ?: recipient.address
if (index < recipients.size - 1) {
title += ", "
}
@@ -0,0 +1,10 @@
package com.moez.QKSMS.data.model
import io.realm.RealmObject
open class PhoneNumber : RealmObject() {
var address: String = ""
var label: String = ""
}
@@ -7,5 +7,7 @@ open class Recipient : RealmObject() {
@PrimaryKey var id: Long = 0
var address: String = ""
var contact: Contact? = null
var lastUpdate: Long = 0
}
@@ -6,6 +6,7 @@ import android.provider.BaseColumns
import android.provider.ContactsContract
import com.moez.QKSMS.common.util.extensions.asFlowable
import com.moez.QKSMS.data.model.Contact
import com.moez.QKSMS.data.model.PhoneNumber
import io.reactivex.Flowable
import io.reactivex.Single
import io.realm.Realm
@@ -16,11 +17,6 @@ import javax.inject.Singleton
@Singleton
class ContactRepository @Inject constructor(val context: Context) {
/**
* Uri for the MMS-SMS recipients table, where there exists only one column (address)
*/
private val URI = Uri.parse("content://mms-sms/canonical-address")
fun findContactUri(address: String): Single<Uri> {
return Flowable.just(address)
.map { address -> Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address)) }
@@ -34,54 +30,49 @@ class ContactRepository @Inject constructor(val context: Context) {
val realm = Realm.getDefaultInstance()
val results = realm.copyFromRealm(realm
.where(Contact::class.java)
.equalTo("inContactsTable", true)
.findAllSorted("name"))
realm.close()
return results
}
fun getContact(recipientId: Long): Flowable<Contact> {
fun getContact(address: String): Flowable<Contact> {
return Flowable.fromPublisher<Contact> { emitter ->
val contact = getContactFromRealm(recipientId) ?: getContactFromDb(recipientId)
contact?.let { emitter.onNext(it) }
getContactBlocking(address)?.let { emitter.onNext(it) }
emitter.onComplete()
}
}
private fun getContactFromRealm(recipientId: Long): Contact? {
fun getContactBlocking(address: String): Contact? {
return getContactFromRealm(address) ?: getContactFromDb(address)
}
private fun getContactFromRealm(address: String): Contact? {
val realm = Realm.getDefaultInstance()
val results = realm.where(Contact::class.java)
.equalTo("recipientId", recipientId)
.equalTo("numbers.address", address)
.findAll()
realm.close()
return results.getOrNull(0)
}
private fun getContactFromDb(recipientId: Long): Contact? {
context.contentResolver.query(Uri.withAppendedPath(URI, recipientId.toString()), null, null, null, null)?.use { recipientCursor ->
if (recipientCursor.moveToFirst()) {
val contact = Contact().apply {
this.recipientId = recipientId
this.address = recipientCursor.getString(0)
}
val contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(contact.address))
val projection = arrayOf(BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.LOOKUP_KEY)
try {
context.contentResolver.query(contactUri, projection, null, null, null).use { contactCursor ->
if (contactCursor.moveToFirst()) {
contact.inContactsTable = true
contact.name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).orEmpty()
contact.lookupKey = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.LOOKUP_KEY)).orEmpty()
}
private fun getContactFromDb(address: String): Contact? {
val contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address))
val projection = arrayOf(BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.LOOKUP_KEY)
try {
context.contentResolver.query(contactUri, projection, null, null, null).use { contactCursor ->
if (contactCursor.moveToFirst()) {
return Contact().apply {
numbers.add(PhoneNumber().apply { this.address = address })
name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).orEmpty()
lookupKey = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.LOOKUP_KEY)).orEmpty()
lastUpdate = System.currentTimeMillis()
}
} catch (e: Exception) {
Timber.w(e)
}
return contact
}
} catch (e: Exception) {
Timber.w(e)
}
return null
@@ -4,6 +4,9 @@ import android.content.Context
import com.moez.QKSMS.data.mapper.CursorToConversation
import com.moez.QKSMS.data.mapper.CursorToMessage
import com.moez.QKSMS.data.mapper.CursorToRecipient
import com.moez.QKSMS.data.model.Conversation
import com.moez.QKSMS.data.model.Message
import com.moez.QKSMS.data.model.Recipient
import io.reactivex.Flowable
import io.realm.Realm
import javax.inject.Inject
@@ -17,7 +20,11 @@ class FullSync @Inject constructor(
override fun buildObservable(params: Unit): Flowable<Long> {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.deleteAll() }
realm.executeTransaction {
realm.delete(Conversation::class.java)
realm.delete(Message::class.java)
realm.delete(Recipient::class.java)
}
realm.close()
return super.buildObservable(params)
@@ -29,6 +29,7 @@ open class PartialSync @Inject constructor(
return Flowable.just(params)
.doOnNext {
Timber.v("Starting sync")
startTime = System.currentTimeMillis()
// We need to set up realm on the io thread, and doOnSubscribe doesn't support setting a custom Scheduler
@@ -70,7 +71,7 @@ open class PartialSync @Inject constructor(
.doOnNext {
realm?.commitTransaction()
realm?.close()
Timber.v("Performed sync in ${TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime)} seconds")
Timber.v("Completed sync in ${TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime)} seconds")
}
.map { 0L }
}
@@ -77,8 +77,8 @@ class AvatarView @JvmOverloads constructor(context: Context, attrs: AttributeSet
}
photo.setImageDrawable(null)
contact?.let { contact ->
GlideApp.with(photo).load(PhoneNumberUtils.stripSeparators(contact.address)).into(photo)
contact?.numbers?.firstOrNull()?.address?.let { address ->
GlideApp.with(photo).load(PhoneNumberUtils.stripSeparators(address)).into(photo)
}
}
}
@@ -116,6 +116,6 @@ class ChipsAdapter @Inject constructor(private val context: Context) : QkAdapter
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.recipientId == new.recipientId
return old.lookupKey == new.lookupKey
}
}
@@ -56,7 +56,7 @@ class ComposeViewModel(threadId: Long) : QkViewModel<ComposeView, ComposeState>(
// Map the selected contacts to a conversation so that we can display the message history
val selectedConversation = selectedContacts
.map { contacts -> contacts.map { it.address } }
.map { contacts -> contacts.map { it.numbers.firstOrNull()?.address ?: "" } }
.flatMapMaybe { addresses -> messageRepo.getOrCreateConversation(addresses) }
// Merges two potential conversation sources (threadId from constructor and contact selection) into a single
@@ -116,7 +116,7 @@ class ComposeViewModel(threadId: Long) : QkViewModel<ComposeView, ComposeState>(
contacts
.filterNot { contact -> selectedContacts.contains(contact) }
.filter { contact ->
contact.name.contains(query, true) || PhoneNumberUtils.compare(contact.address, query.toString())
contact.name.contains(query, true) || PhoneNumberUtils.compare(contact.numbers.firstOrNull()?.address, query.toString())
}
})
.subscribeOn(Schedulers.computation())
@@ -32,11 +32,11 @@ class ContactAdapter @Inject constructor(private val context: Context) : QkAdapt
view.avatar.contact = contact
view.name.text = contact.name
view.address.text = contact.address
view.address.text = contact.numbers.map { it.address }.toString()
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.recipientId == new.recipientId
return old.lookupKey == new.lookupKey
}
}
@@ -47,7 +47,7 @@ class DetailedChipView(context: Context) : RelativeLayout(context) {
fun setContact(contact: Contact) {
avatar.contact = contact
name.text = contact.name
info.text = contact.address
info.text = contact.numbers.map { it.address }.toString()
}
fun show() {
@@ -14,6 +14,7 @@ import com.moez.QKSMS.common.util.extensions.setBackgroundTint
import com.moez.QKSMS.common.util.extensions.setPadding
import com.moez.QKSMS.data.model.Contact
import com.moez.QKSMS.data.model.Message
import com.moez.QKSMS.data.model.PhoneNumber
import com.moez.QKSMS.presentation.common.base.QkViewHolder
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
@@ -60,9 +61,9 @@ class MessagesAdapter @Inject constructor(
}
if (viewType != VIEWTYPE_ME) {
val contact = Contact()
contact.address = people[viewType]
view.avatar.contact = contact
view.avatar.contact = Contact().apply {
numbers.add(PhoneNumber().apply { address = people[viewType] })
}
}
return QkViewHolder(view)
@@ -10,6 +10,7 @@ import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.DateFormatter
import com.moez.QKSMS.data.model.Contact
import com.moez.QKSMS.data.model.InboxItem
import com.moez.QKSMS.data.model.PhoneNumber
import com.moez.QKSMS.data.repository.MessageRepository
import com.moez.QKSMS.presentation.Navigator
import com.moez.QKSMS.presentation.common.base.FlowableAdapter
@@ -63,7 +64,9 @@ class ConversationsAdapter @Inject constructor(
RxView.clicks(view).subscribe { navigator.showConversation(message.threadId) }
RxView.longClicks(view).subscribe { longClicks.onNext(conversation.id) }
view.avatars.contacts = conversation.recipients.map { recipient -> Contact().apply { address = recipient.address } }
view.avatars.contacts = conversation.recipients.map { recipient ->
recipient.contact ?: Contact().apply { numbers.add(PhoneNumber().apply { address = recipient.address }) }
}
view.title.text = conversation.getTitle()
view.date.text = dateFormatter.getConversationTimestamp(message.date)
view.snippet.text = message.body