Keep contacts in sync

Fixes #329
This commit is contained in:
Moez Bhatti
2019-11-24 15:30:25 -05:00
parent 25cff7e346
commit 13c8ba3e78
10 changed files with 27 additions and 75 deletions
@@ -23,33 +23,28 @@ import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.provider.ContactsContract
import com.moez.QKSMS.repository.SyncRepository
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.BehaviorSubject
import javax.inject.Inject
/**
* Listens for a contact being added, and then syncs it to Realm
*
* TODO: Stop listening automatically. Currently, this will only happen if the contact is added
*/
class ContactAddedListenerImpl @Inject constructor(
private val context: Context,
private val syncRepo: SyncRepository
private val context: Context
) : ContactAddedListener {
companion object {
private val URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
}
override fun listen(address: String): Observable<*> {
override fun listen(): Observable<*> {
return ContactContentObserver(context).observable
.filter { syncRepo.syncContact(address) }
}
private class ContactContentObserver(context: Context) : ContentObserver(Handler()) {
private val subject = PublishSubject.create<Unit>()
private val subject = BehaviorSubject.createDefault<Unit>(Unit)
val observable: Observable<Unit> = subject
.doOnSubscribe { context.contentResolver.registerContentObserver(URI, true, this) }
@@ -66,4 +61,4 @@ class ContactAddedListenerImpl @Inject constructor(
}
}
}
@@ -65,7 +65,7 @@ class SyncRepositoryImpl @Inject constructor(
) : SyncRepository {
override val syncProgress: Subject<SyncRepository.SyncProgress> =
BehaviorSubject.createDefault(SyncRepository.SyncProgress.Idle())
BehaviorSubject.createDefault(SyncRepository.SyncProgress.Idle)
override fun syncMessages() {
@@ -185,7 +185,7 @@ class SyncRepositoryImpl @Inject constructor(
// Only delete this after the sync has successfully completed
oldBlockedSenders.delete()
syncProgress.onNext(SyncRepository.SyncProgress.Idle())
syncProgress.onNext(SyncRepository.SyncProgress.Idle)
}
override fun syncMessage(uri: Uri): Message? {
@@ -259,32 +259,6 @@ class SyncRepositoryImpl @Inject constructor(
}
}
override fun syncContact(address: String): Boolean {
// See if there's a contact that matches this phone number
var contact = getContacts().find { contact ->
contact.numbers.any { number -> phoneNumberUtils.compare(number.address, address) }
} ?: return false
Realm.getDefaultInstance().use { realm ->
val recipients = realm.where(Recipient::class.java).findAll().filter { recipient ->
contact.numbers.any { number ->
phoneNumberUtils.compare(recipient.address, number.address)
}
}
realm.executeTransaction {
contact = realm.copyToRealmOrUpdate(contact)
// Update all the matching recipients with the new contact
recipients.forEach { recipient -> recipient.contact = contact }
realm.insertOrUpdate(recipients)
}
}
return true
}
private fun getContacts(): List<Contact> {
val defaultNumberIds = Realm.getDefaultInstance().use { realm ->
realm.where(PhoneNumber::class.java)
@@ -21,7 +21,6 @@ package com.moez.QKSMS.interactor
import com.moez.QKSMS.repository.SyncRepository
import io.reactivex.Flowable
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class SyncContacts @Inject constructor(private val syncManager: SyncRepository) : Interactor<Unit>() {
@@ -30,8 +29,7 @@ class SyncContacts @Inject constructor(private val syncManager: SyncRepository)
return Flowable.just(System.currentTimeMillis())
.doOnNext { syncManager.syncContacts() }
.map { startTime -> System.currentTimeMillis() - startTime }
.map { elapsed -> TimeUnit.MILLISECONDS.toSeconds(elapsed) }
.doOnNext { seconds -> Timber.v("Completed sync in $seconds seconds") }
.doOnNext { duration -> Timber.v("Completed sync in ${duration}ms") }
}
}
@@ -22,6 +22,6 @@ import io.reactivex.Observable
interface ContactAddedListener {
fun listen(address: String): Observable<*>
fun listen(): Observable<*>
}
}
@@ -25,7 +25,7 @@ import io.reactivex.Observable
interface SyncRepository {
sealed class SyncProgress {
class Idle : SyncProgress()
object Idle : SyncProgress()
data class Running(val max: Int, val progress: Int, val indeterminate: Boolean) : SyncProgress()
}
@@ -37,11 +37,4 @@ interface SyncRepository {
fun syncContacts()
/**
* Syncs a single contact to the Realm
*
* Return false if the contact couldn't be found
*/
fun syncContact(address: String): Boolean
}
}
@@ -27,7 +27,6 @@ import com.moez.QKSMS.feature.compose.editing.ComposeItem
import com.moez.QKSMS.feature.compose.editing.PhoneNumberAction
import com.moez.QKSMS.filter.ContactFilter
import com.moez.QKSMS.filter.ContactGroupFilter
import com.moez.QKSMS.interactor.SyncContacts
import com.moez.QKSMS.interactor.SetDefaultPhoneNumber
import com.moez.QKSMS.model.Contact
import com.moez.QKSMS.model.ContactGroup
@@ -50,7 +49,6 @@ import javax.inject.Inject
class ContactsViewModel @Inject constructor(
sharing: Boolean,
serializedChips: HashMap<String, String?>,
syncContacts: SyncContacts,
private val contactFilter: ContactFilter,
private val contactGroupFilter: ContactGroupFilter,
private val contactsRepo: ContactRepository,
@@ -76,10 +74,6 @@ class ContactsViewModel @Inject constructor(
private var shouldOpenKeyboard: Boolean = true
init {
syncContacts.execute(Unit)
}
override fun bindView(view: ContactsContract) {
super.bindView(view)
@@ -26,14 +26,12 @@ import com.moez.QKSMS.extensions.mapNotNull
import com.moez.QKSMS.interactor.DeleteConversations
import com.moez.QKSMS.interactor.MarkArchived
import com.moez.QKSMS.interactor.MarkUnarchived
import com.moez.QKSMS.listener.ContactAddedListener
import com.moez.QKSMS.manager.PermissionManager
import com.moez.QKSMS.model.Conversation
import com.moez.QKSMS.repository.ConversationRepository
import com.moez.QKSMS.repository.MessageRepository
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.reactivex.subjects.BehaviorSubject
@@ -44,7 +42,6 @@ import javax.inject.Named
class ConversationInfoPresenter @Inject constructor(
@Named("threadId") threadId: Long,
messageRepo: MessageRepository,
private val contactAddedListener: ContactAddedListener,
private val conversationRepo: ConversationRepository,
private val deleteConversations: DeleteConversations,
private val markArchived: MarkArchived,
@@ -105,16 +102,9 @@ class ConversationInfoPresenter @Inject constructor(
// Add or display the contact
view.recipientClicks()
.mapNotNull(conversationRepo::getRecipient)
.flatMap { recipient ->
val lookupKey = recipient.contact?.lookupKey
if (lookupKey != null) {
navigator.showContact(lookupKey)
Observable.empty<Unit>()
} else {
// Allow the user to add the contact, then listen for changes
navigator.addContact(recipient.address)
contactAddedListener.listen(recipient.address)
}
.doOnNext { recipient ->
recipient.contact?.lookupKey?.let(navigator::showContact)
?: navigator.addContact(recipient.address)
}
.autoDisposable(view.scope(Lifecycle.Event.ON_DESTROY)) // ... this should be the default
.subscribe()
@@ -29,7 +29,7 @@ data class MainState(
val drawerOpen: Boolean = false,
val upgraded: Boolean = true,
val showRating: Boolean = false,
val syncing: SyncRepository.SyncProgress = SyncRepository.SyncProgress.Idle(),
val syncing: SyncRepository.SyncProgress = SyncRepository.SyncProgress.Idle,
val defaultSms: Boolean = true,
val smsPermission: Boolean = true,
val contactPermission: Boolean = true
@@ -33,6 +33,7 @@ import com.moez.QKSMS.interactor.MarkUnarchived
import com.moez.QKSMS.interactor.MarkUnpinned
import com.moez.QKSMS.interactor.MarkUnread
import com.moez.QKSMS.interactor.MigratePreferences
import com.moez.QKSMS.interactor.SyncContacts
import com.moez.QKSMS.interactor.SyncMessages
import com.moez.QKSMS.listener.ContactAddedListener
import com.moez.QKSMS.manager.ChangelogManager
@@ -55,10 +56,10 @@ import javax.inject.Inject
class MainViewModel @Inject constructor(
billingManager: BillingManager,
contactAddedListener: ContactAddedListener,
markAllSeen: MarkAllSeen,
migratePreferences: MigratePreferences,
syncRepository: SyncRepository,
private val contactAddedListener: ContactAddedListener,
private val changelogManager: ChangelogManager,
private val conversationRepo: ConversationRepository,
private val deleteConversations: DeleteConversations,
@@ -72,6 +73,7 @@ class MainViewModel @Inject constructor(
private val permissionManager: PermissionManager,
private val prefs: Preferences,
private val ratingManager: RatingManager,
private val syncContacts: SyncContacts,
private val syncMessages: SyncMessages
) : QkViewModel<MainView, MainState>(MainState(page = Inbox(data = conversationRepo.getConversations()))) {
@@ -81,6 +83,7 @@ class MainViewModel @Inject constructor(
disposables += markArchived
disposables += markUnarchived
disposables += migratePreferences
disposables += syncContacts
disposables += syncMessages
// Show the syncing UI
@@ -109,6 +112,12 @@ class MainViewModel @Inject constructor(
syncMessages.execute(Unit)
}
// Sync contacts when we detect a change
disposables += contactAddedListener.listen()
.debounce(1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.subscribe { syncContacts.execute(Unit) }
ratingManager.addSession()
markAllSeen.execute(Unit)
}
@@ -287,7 +296,6 @@ class MainViewModel @Inject constructor(
.map { conversation -> conversation.recipients }
.mapNotNull { recipients -> recipients[0]?.address?.takeIf { recipients.size == 1 } }
.doOnNext(navigator::addContact)
.flatMap(contactAddedListener::listen)
.autoDisposable(view.scope())
.subscribe()
@@ -42,5 +42,5 @@ data class SettingsState(
val mobileOnly: Boolean = false,
val maxMmsSizeSummary: String = "100KB",
val maxMmsSizeId: Int = 100,
val syncProgress: SyncRepository.SyncProgress = SyncRepository.SyncProgress.Idle()
val syncProgress: SyncRepository.SyncProgress = SyncRepository.SyncProgress.Idle
)