Build phone number picker

This commit is contained in:
moezbhatti
2019-11-07 02:44:19 -05:00
committed by Moez Bhatti
parent 058d12d3bb
commit bb816209ba
21 changed files with 531 additions and 28 deletions
-1
View File
@@ -79,7 +79,6 @@ dependencies {
// coroutines // coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:$coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-reactive:$coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-reactive:$coroutines_version"
@@ -34,6 +34,7 @@ class CursorToContactImpl @Inject constructor(
companion object { companion object {
val URI = Phone.CONTENT_URI val URI = Phone.CONTENT_URI
val PROJECTION = arrayOf( val PROJECTION = arrayOf(
Phone._ID,
Phone.LOOKUP_KEY, Phone.LOOKUP_KEY,
Phone.ACCOUNT_TYPE_AND_DATA_SET, Phone.ACCOUNT_TYPE_AND_DATA_SET,
Phone.NUMBER, Phone.NUMBER,
@@ -44,20 +45,22 @@ class CursorToContactImpl @Inject constructor(
Phone.CONTACT_LAST_UPDATED_TIMESTAMP Phone.CONTACT_LAST_UPDATED_TIMESTAMP
) )
const val COLUMN_LOOKUP_KEY = 0 const val COLUMN_ID = 0
const val COLUMN_ACCOUNT_TYPE = 1 const val COLUMN_LOOKUP_KEY = 1
const val COLUMN_NUMBER = 2 const val COLUMN_ACCOUNT_TYPE = 2
const val COLUMN_TYPE = 3 const val COLUMN_NUMBER = 3
const val COLUMN_LABEL = 4 const val COLUMN_TYPE = 4
const val COLUMN_DISPLAY_NAME = 5 const val COLUMN_LABEL = 5
const val COLUMN_STARRED = 6 const val COLUMN_DISPLAY_NAME = 6
const val CONTACT_LAST_UPDATED = 7 const val COLUMN_STARRED = 7
const val CONTACT_LAST_UPDATED = 8
} }
override fun map(from: Cursor) = Contact().apply { override fun map(from: Cursor) = Contact().apply {
lookupKey = from.getString(COLUMN_LOOKUP_KEY) lookupKey = from.getString(COLUMN_LOOKUP_KEY)
name = from.getString(COLUMN_DISPLAY_NAME) ?: "" name = from.getString(COLUMN_DISPLAY_NAME) ?: ""
numbers.add(PhoneNumber( numbers.add(PhoneNumber(
id = from.getLong(COLUMN_ID),
accountType = from.getString(COLUMN_ACCOUNT_TYPE), accountType = from.getString(COLUMN_ACCOUNT_TYPE),
address = from.getString(COLUMN_NUMBER) ?: "", address = from.getString(COLUMN_NUMBER) ?: "",
type = Phone.getTypeLabel(context.resources, from.getInt(COLUMN_TYPE), type = Phone.getTypeLabel(context.resources, from.getInt(COLUMN_TYPE),
@@ -128,7 +128,9 @@ class QkRealmMigration : RealmMigration {
?.addField("starred", Boolean::class.java, FieldAttribute.REQUIRED) ?.addField("starred", Boolean::class.java, FieldAttribute.REQUIRED)
realm.schema.get("PhoneNumber") realm.schema.get("PhoneNumber")
?.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
?.addField("accountType", String::class.java, FieldAttribute.REQUIRED) ?.addField("accountType", String::class.java, FieldAttribute.REQUIRED)
?.addField("isDefault", Boolean::class.java, FieldAttribute.REQUIRED)
version++ version++
} }
@@ -137,4 +137,20 @@ class ContactRepositoryImpl @Inject constructor(
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
} }
override fun setDefaultPhoneNumber(lookupKey: String, phoneNumberId: Long) {
Realm.getDefaultInstance().use { realm ->
realm.refresh()
val contact = realm.where(Contact::class.java)
.equalTo("lookupKey", lookupKey)
.findFirst()
?: return
realm.executeTransaction {
contact.numbers.forEach { number ->
number.isDefault = number.id == phoneNumberId
}
}
}
}
} }
@@ -243,7 +243,7 @@ class SyncRepositoryImpl @Inject constructor(
realm.delete(Contact::class.java) realm.delete(Contact::class.java)
realm.delete(ContactGroup::class.java) realm.delete(ContactGroup::class.java)
contacts = realm.copyToRealm(contacts) contacts = realm.copyToRealmOrUpdate(contacts)
realm.insertOrUpdate(getContactGroups(contacts)) realm.insertOrUpdate(getContactGroups(contacts))
// Update all the recipients with the new contacts // Update all the recipients with the new contacts
@@ -286,6 +286,13 @@ class SyncRepositoryImpl @Inject constructor(
} }
private fun getContacts(): List<Contact> { private fun getContacts(): List<Contact> {
val defaultNumberIds = Realm.getDefaultInstance().use { realm ->
realm.where(PhoneNumber::class.java)
.equalTo("isDefault", true)
.findAll()
.map { number -> number.id }
}
return cursorToContact.getContactsCursor() return cursorToContact.getContactsCursor()
?.map { cursor -> cursorToContact.map(cursor) } ?.map { cursor -> cursorToContact.map(cursor) }
?.groupBy { contact -> contact.lookupKey } ?.groupBy { contact -> contact.lookupKey }
@@ -297,10 +304,12 @@ class SyncRepositoryImpl @Inject constructor(
.flatMap { it.numbers } .flatMap { it.numbers }
.sortedBy { it.accountType } .sortedBy { it.accountType }
.forEach { number -> .forEach { number ->
number.isDefault = defaultNumberIds.any { id -> id == number.id }
val duplicate = uniqueNumbers.any { other -> val duplicate = uniqueNumbers.any { other ->
number.accountType != other.accountType number.accountType != other.accountType
&& phoneNumberUtils.compare(number.address, other.address) && phoneNumberUtils.compare(number.address, other.address)
} }
if (!duplicate) { if (!duplicate) {
uniqueNumbers += number uniqueNumbers += number
} }
-1
View File
@@ -53,7 +53,6 @@ dependencies {
// coroutines // coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:$coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-reactive:$coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-reactive:$coroutines_version"
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2019 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 com.moez.QKSMS.interactor
import com.moez.QKSMS.repository.ContactRepository
import io.reactivex.Flowable
import javax.inject.Inject
class SetDefaultPhoneNumber @Inject constructor(
private val contactRepo: ContactRepository
) : Interactor<SetDefaultPhoneNumber.Params>() {
data class Params(val lookupKey: String, val phoneNumberId: Long)
override fun buildObservable(params: Params): Flowable<*> {
return Flowable.just(params)
.doOnNext { (lookupKey, phoneNumberId) ->
contactRepo.setDefaultPhoneNumber(lookupKey, phoneNumberId)
}
}
}
@@ -28,4 +28,8 @@ open class Contact(
var name: String = "", var name: String = "",
var starred: Boolean = false, var starred: Boolean = false,
var lastUpdate: Long = 0 var lastUpdate: Long = 0
) : RealmObject() ) : RealmObject() {
fun getDefaultNumber(): PhoneNumber? = numbers.find { number -> number.isDefault }
}
@@ -19,9 +19,12 @@
package com.moez.QKSMS.model package com.moez.QKSMS.model
import io.realm.RealmObject import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class PhoneNumber( open class PhoneNumber(
@PrimaryKey var id: Long = 0,
var accountType: String = "", var accountType: String = "",
var address: String = "", var address: String = "",
var type: String = "" var type: String = "",
var isDefault: Boolean = false
) : RealmObject() ) : RealmObject()
@@ -35,4 +35,6 @@ interface ContactRepository {
fun getUnmanagedContactGroups(): Observable<List<ContactGroup>> fun getUnmanagedContactGroups(): Observable<List<ContactGroup>>
fun setDefaultPhoneNumber(lookupKey: String, phoneNumberId: Long)
} }
@@ -0,0 +1,105 @@
/*
* Copyright (C) 2019 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 com.moez.QKSMS.common.widget
import android.app.Activity
import android.view.LayoutInflater
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkAdapter
import kotlinx.android.synthetic.main.qk_dialog.view.*
class QkDialog(private val context: Activity) : AlertDialog(context) {
private val view = LayoutInflater.from(context).inflate(R.layout.qk_dialog, null)
@StringRes
var titleRes: Int? = null
set(value) {
field = value
title = value?.let(context::getString)
}
var title: String? = null
set(value) {
field = value
view.title.text = value
view.title.isVisible = !value.isNullOrBlank()
}
@StringRes
var subtitleRes: Int? = null
set(value) {
field = value
subtitle = value?.let(context::getString)
}
var subtitle: String? = null
set(value) {
field = value
view.subtitle.text = value
view.subtitle.isVisible = !value.isNullOrBlank()
}
var adapter: QkAdapter<*>? = null
set(value) {
field = value
view.list.isVisible = value != null
view.list.adapter = value
}
var positiveButtonListener: (() -> Unit)? = null
@StringRes
var positiveButton: Int? = null
set(value) {
field = value
value?.run(view.positiveButton::setText)
view.positiveButton.isVisible = value != null
view.positiveButton.setOnClickListener {
positiveButtonListener?.invoke() ?: dismiss()
}
}
var negativeButtonListener: (() -> Unit)? = null
@StringRes
var negativeButton: Int? = null
set(value) {
field = value
value?.run(view.negativeButton::setText)
view.negativeButton.isVisible = value != null
view.negativeButton.setOnClickListener {
negativeButtonListener?.invoke() ?: dismiss()
}
}
var cancelListener: (() -> Unit)? = null
set(value) {
field = value
setOnCancelListener { value?.invoke() }
}
init {
setView(view)
}
}
@@ -54,10 +54,14 @@ import com.moez.QKSMS.common.util.extensions.setBackgroundTint
import com.moez.QKSMS.common.util.extensions.setTint import com.moez.QKSMS.common.util.extensions.setTint
import com.moez.QKSMS.common.util.extensions.setVisible import com.moez.QKSMS.common.util.extensions.setVisible
import com.moez.QKSMS.common.util.extensions.showKeyboard import com.moez.QKSMS.common.util.extensions.showKeyboard
import com.moez.QKSMS.common.widget.QkDialog
import com.moez.QKSMS.extensions.Optional
import com.moez.QKSMS.feature.compose.editing.Chip import com.moez.QKSMS.feature.compose.editing.Chip
import com.moez.QKSMS.feature.compose.editing.ChipsAdapter import com.moez.QKSMS.feature.compose.editing.ChipsAdapter
import com.moez.QKSMS.feature.compose.editing.ComposeItem import com.moez.QKSMS.feature.compose.editing.ComposeItem
import com.moez.QKSMS.feature.compose.editing.ComposeItemAdapter import com.moez.QKSMS.feature.compose.editing.ComposeItemAdapter
import com.moez.QKSMS.feature.compose.editing.PhoneNumberAction
import com.moez.QKSMS.feature.compose.editing.PhoneNumberPickerAdapter
import com.moez.QKSMS.model.Attachment import com.moez.QKSMS.model.Attachment
import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable import com.uber.autodispose.autoDisposable
@@ -84,13 +88,17 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
@Inject lateinit var dateFormatter: DateFormatter @Inject lateinit var dateFormatter: DateFormatter
@Inject lateinit var messageAdapter: MessagesAdapter @Inject lateinit var messageAdapter: MessagesAdapter
@Inject lateinit var navigator: Navigator @Inject lateinit var navigator: Navigator
@Inject lateinit var phoneNumberAdapter: PhoneNumberPickerAdapter
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var viewModelFactory: ViewModelProvider.Factory
override val activityVisibleIntent: Subject<Boolean> = PublishSubject.create() override val activityVisibleIntent: Subject<Boolean> = PublishSubject.create()
override val queryChangedIntent: Observable<CharSequence> by lazy { search.textChanges() } override val queryChangedIntent: Observable<CharSequence> by lazy { search.textChanges() }
override val queryBackspaceIntent: Observable<*> by lazy { search.backspaces } override val queryBackspaceIntent: Observable<*> by lazy { search.backspaces }
override val queryEditorActionIntent: Observable<Int> by lazy { search.editorActions() } override val queryEditorActionIntent: Observable<Int> by lazy { search.editorActions() }
override val chipSelectedIntent: Subject<ComposeItem> by lazy { contactsAdapter.itemSelected } override val composeItemPressedIntent: Subject<ComposeItem> by lazy { contactsAdapter.clicks }
override val composeItemLongPressedIntent: Subject<ComposeItem> by lazy { contactsAdapter.longClicks }
override val phoneNumberSelectedIntent: Subject<Optional<Long>> by lazy { phoneNumberAdapter.selectedItemChanges }
override val phoneNumberActionIntent: Subject<PhoneNumberAction> = PublishSubject.create()
override val chipDeletedIntent: Subject<Chip> by lazy { chipsAdapter.chipDeleted } override val chipDeletedIntent: Subject<Chip> by lazy { chipsAdapter.chipDeleted }
override val menuReadyIntent: Observable<Unit> = menu.map { Unit } override val menuReadyIntent: Observable<Unit> = menu.map { Unit }
override val optionsItemIntent: Subject<Int> = PublishSubject.create() override val optionsItemIntent: Subject<Int> = PublishSubject.create()
@@ -116,6 +124,18 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
override val viewQksmsPlusIntent: Subject<Unit> = PublishSubject.create() override val viewQksmsPlusIntent: Subject<Unit> = PublishSubject.create()
override val backPressedIntent: Subject<Unit> = PublishSubject.create() override val backPressedIntent: Subject<Unit> = PublishSubject.create()
private val phoneNumberDialog by lazy {
QkDialog(this).apply {
titleRes = R.string.compose_number_picker_title
adapter = phoneNumberAdapter
positiveButton = R.string.compose_number_picker_always
positiveButtonListener = { phoneNumberActionIntent.onNext(PhoneNumberAction.ALWAYS) }
negativeButton = R.string.compose_number_picker_once
negativeButtonListener = { phoneNumberActionIntent.onNext(PhoneNumberAction.JUST_ONCE) }
cancelListener = { phoneNumberActionIntent.onNext(PhoneNumberAction.CANCEL) }
}
}
private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory)[ComposeViewModel::class.java] } private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory)[ComposeViewModel::class.java] }
private var cameraDestination: Uri? = null private var cameraDestination: Uri? = null
@@ -202,8 +222,10 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
if (state.editingMode && contacts.adapter == null) contacts.adapter = contactsAdapter if (state.editingMode && contacts.adapter == null) contacts.adapter = contactsAdapter
toolbar.menu.findItem(R.id.add)?.isVisible = state.editingMode && !state.searching toolbar.menu.findItem(R.id.add)?.isVisible = state.editingMode && !state.searching
toolbar.menu.findItem(R.id.call)?.isVisible = !state.editingMode && state.selectedMessages == 0 && state.query.isEmpty() toolbar.menu.findItem(R.id.call)?.isVisible = !state.editingMode && state.selectedMessages == 0
toolbar.menu.findItem(R.id.info)?.isVisible = !state.editingMode && state.selectedMessages == 0 && state.query.isEmpty() && state.query.isEmpty()
toolbar.menu.findItem(R.id.info)?.isVisible = !state.editingMode && state.selectedMessages == 0
&& state.query.isEmpty()
toolbar.menu.findItem(R.id.copy)?.isVisible = !state.editingMode && state.selectedMessages == 1 toolbar.menu.findItem(R.id.copy)?.isVisible = !state.editingMode && state.selectedMessages == 1
toolbar.menu.findItem(R.id.details)?.isVisible = !state.editingMode && state.selectedMessages == 1 toolbar.menu.findItem(R.id.details)?.isVisible = !state.editingMode && state.selectedMessages == 1
toolbar.menu.findItem(R.id.delete)?.isVisible = !state.editingMode && state.selectedMessages > 0 toolbar.menu.findItem(R.id.delete)?.isVisible = !state.editingMode && state.selectedMessages > 0
@@ -219,6 +241,14 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
chipsAdapter.data = state.selectedChips chipsAdapter.data = state.selectedChips
contactsAdapter.data = state.composeItems contactsAdapter.data = state.composeItems
if (state.selectedContact != null && !phoneNumberDialog.isShowing) {
phoneNumberAdapter.data = state.selectedContact.numbers
phoneNumberDialog.subtitle = state.selectedContact.name
phoneNumberDialog.show()
} else if (state.selectedContact == null && phoneNumberDialog.isShowing) {
phoneNumberDialog.dismiss()
}
loading.setVisible(state.loading) loading.setVisible(state.loading)
sendAsGroup.setVisible(state.editingMode && state.selectedChips.size >= 2) sendAsGroup.setVisible(state.editingMode && state.selectedChips.size >= 2)
@@ -282,7 +312,8 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
calendar.set(Calendar.HOUR_OF_DAY, hour) calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, minute) calendar.set(Calendar.MINUTE, minute)
scheduleSelectedIntent.onNext(calendar.timeInMillis) scheduleSelectedIntent.onNext(calendar.timeInMillis)
}, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), DateFormat.is24HourFormat(this)).show() }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), DateFormat.is24HourFormat(this))
.show()
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show() }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show()
} }
@@ -22,6 +22,7 @@ import com.moez.QKSMS.compat.SubscriptionInfoCompat
import com.moez.QKSMS.feature.compose.editing.Chip import com.moez.QKSMS.feature.compose.editing.Chip
import com.moez.QKSMS.feature.compose.editing.ComposeItem import com.moez.QKSMS.feature.compose.editing.ComposeItem
import com.moez.QKSMS.model.Attachment import com.moez.QKSMS.model.Attachment
import com.moez.QKSMS.model.Contact
import com.moez.QKSMS.model.Conversation import com.moez.QKSMS.model.Conversation
import com.moez.QKSMS.model.Message import com.moez.QKSMS.model.Message
import io.realm.RealmResults import io.realm.RealmResults
@@ -32,6 +33,7 @@ data class ComposeState(
val searching: Boolean = false, val searching: Boolean = false,
val composeItems: List<ComposeItem> = ArrayList(), val composeItems: List<ComposeItem> = ArrayList(),
val selectedConversation: Long = 0, val selectedConversation: Long = 0,
val selectedContact: Contact? = null, // For phone number picker
val selectedChips: List<Chip> = ArrayList(), val selectedChips: List<Chip> = ArrayList(),
val sendAsGroup: Boolean = true, val sendAsGroup: Boolean = true,
val conversationtitle: String = "", val conversationtitle: String = "",
@@ -22,8 +22,10 @@ import android.net.Uri
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.core.view.inputmethod.InputContentInfoCompat import androidx.core.view.inputmethod.InputContentInfoCompat
import com.moez.QKSMS.common.base.QkView import com.moez.QKSMS.common.base.QkView
import com.moez.QKSMS.extensions.Optional
import com.moez.QKSMS.feature.compose.editing.Chip import com.moez.QKSMS.feature.compose.editing.Chip
import com.moez.QKSMS.feature.compose.editing.ComposeItem import com.moez.QKSMS.feature.compose.editing.ComposeItem
import com.moez.QKSMS.feature.compose.editing.PhoneNumberAction
import com.moez.QKSMS.model.Attachment import com.moez.QKSMS.model.Attachment
import io.reactivex.Observable import io.reactivex.Observable
import io.reactivex.subjects.Subject import io.reactivex.subjects.Subject
@@ -34,7 +36,10 @@ interface ComposeView : QkView<ComposeState> {
val queryChangedIntent: Observable<CharSequence> val queryChangedIntent: Observable<CharSequence>
val queryBackspaceIntent: Observable<*> val queryBackspaceIntent: Observable<*>
val queryEditorActionIntent: Observable<Int> val queryEditorActionIntent: Observable<Int>
val chipSelectedIntent: Subject<ComposeItem> val composeItemPressedIntent: Subject<ComposeItem>
val composeItemLongPressedIntent: Subject<ComposeItem>
val phoneNumberSelectedIntent: Subject<Optional<Long>>
val phoneNumberActionIntent: Subject<PhoneNumberAction>
val chipDeletedIntent: Subject<Chip> val chipDeletedIntent: Subject<Chip>
val menuReadyIntent: Observable<Unit> val menuReadyIntent: Observable<Unit>
val optionsItemIntent: Observable<Int> val optionsItemIntent: Observable<Int>
@@ -40,6 +40,7 @@ import com.moez.QKSMS.extensions.removeAccents
import com.moez.QKSMS.feature.compose.editing.Chip import com.moez.QKSMS.feature.compose.editing.Chip
import com.moez.QKSMS.feature.compose.editing.ComposeItem import com.moez.QKSMS.feature.compose.editing.ComposeItem
import com.moez.QKSMS.feature.compose.editing.ComposeItem.* 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.ContactFilter
import com.moez.QKSMS.filter.ContactGroupFilter import com.moez.QKSMS.filter.ContactGroupFilter
import com.moez.QKSMS.interactor.AddScheduledMessage import com.moez.QKSMS.interactor.AddScheduledMessage
@@ -49,6 +50,7 @@ import com.moez.QKSMS.interactor.DeleteMessages
import com.moez.QKSMS.interactor.MarkRead import com.moez.QKSMS.interactor.MarkRead
import com.moez.QKSMS.interactor.RetrySending import com.moez.QKSMS.interactor.RetrySending
import com.moez.QKSMS.interactor.SendMessage import com.moez.QKSMS.interactor.SendMessage
import com.moez.QKSMS.interactor.SetDefaultPhoneNumber
import com.moez.QKSMS.manager.ActiveConversationManager import com.moez.QKSMS.manager.ActiveConversationManager
import com.moez.QKSMS.manager.PermissionManager import com.moez.QKSMS.manager.PermissionManager
import com.moez.QKSMS.model.Attachment import com.moez.QKSMS.model.Attachment
@@ -77,6 +79,8 @@ import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject import io.reactivex.subjects.Subject
import io.realm.RealmList import io.realm.RealmList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.rx2.awaitFirst
import timber.log.Timber import timber.log.Timber
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
@@ -107,6 +111,7 @@ class ComposeViewModel @Inject constructor(
private val prefs: Preferences, private val prefs: Preferences,
private val retrySending: RetrySending, private val retrySending: RetrySending,
private val sendMessage: SendMessage, private val sendMessage: SendMessage,
private val setDefaultPhoneNumber: SetDefaultPhoneNumber,
private val subscriptionManager: SubscriptionManagerCompat, private val subscriptionManager: SubscriptionManagerCompat,
private val syncContacts: ContactSync private val syncContacts: ContactSync
) : QkViewModel<ComposeView, ComposeState>(ComposeState( ) : QkViewModel<ComposeView, ComposeState>(ComposeState(
@@ -310,18 +315,49 @@ class ComposeViewModel @Inject constructor(
.autoDisposable(view.scope()) .autoDisposable(view.scope())
.subscribe() .subscribe()
// Enter the first contact suggestion if the enter button is pressed, and enter contacts that are selected // Listen for ComposeItems being selected, and then send them off to the number picker dialog in case
// the user needs to select a phone number
view.queryEditorActionIntent view.queryEditorActionIntent
.filter { actionId -> actionId == EditorInfo.IME_ACTION_DONE } .filter { actionId -> actionId == EditorInfo.IME_ACTION_DONE }
.withLatestFrom(state) { _, state -> state } .withLatestFrom(state) { _, state -> state }
.mapNotNull { state -> state.composeItems.firstOrNull() } .mapNotNull { state -> state.composeItems.firstOrNull() }
.mergeWith(view.chipSelectedIntent) .mergeWith(view.composeItemPressedIntent)
.map { composeItem -> composeItem to false }
.mergeWith(view.composeItemLongPressedIntent.map { composeItem -> composeItem to true })
.observeOn(Schedulers.io())
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.autoDisposable(view.scope()) .autoDisposable(view.scope())
.subscribe { composeItem -> .subscribe { (composeItem, force) ->
newState { copy(searching = false) } val contacts = composeItem.getContacts()
chipsReducer.onNext { chips -> val newChips = contacts.map { contact ->
chips + composeItem.getContacts().map { Chip(it.numbers.first()?.address.orEmpty(), it) } if (contact.numbers.size == 1 || contact.getDefaultNumber() != null && !force) {
val number = contact.getDefaultNumber() ?: contact.numbers[0]!!
Chip(number.address, contact)
} else {
runBlocking {
newState { copy(selectedContact = contact) }
val action = view.phoneNumberActionIntent.awaitFirst()
newState { copy(selectedContact = null) }
val numberId = view.phoneNumberSelectedIntent.awaitFirst().value
val number = contact.numbers.find { number -> number.id == numberId }
if (action == PhoneNumberAction.CANCEL || number == null) {
return@runBlocking null
}
if (action == PhoneNumberAction.ALWAYS) {
val params = SetDefaultPhoneNumber.Params(contact.lookupKey, number.id)
setDefaultPhoneNumber.execute(params)
}
Chip(number.address, contact)
} ?: return@subscribe
}
} }
newState { copy(searching = false) }
chipsReducer.onNext { chips -> chips + newChips }
} }
// Update the list of selected contacts when a new contact is selected or an existing one is deselected // Update the list of selected contacts when a new contact is selected or an existing one is deselected
@@ -40,7 +40,8 @@ import javax.inject.Inject
class ComposeItemAdapter @Inject constructor(private val colors: Colors) : QkAdapter<ComposeItem>() { class ComposeItemAdapter @Inject constructor(private val colors: Colors) : QkAdapter<ComposeItem>() {
val itemSelected: Subject<ComposeItem> = PublishSubject.create() val clicks: Subject<ComposeItem> = PublishSubject.create()
val longClicks: Subject<ComposeItem> = PublishSubject.create()
private val numbersViewPool = RecyclerView.RecycledViewPool() private val numbersViewPool = RecyclerView.RecycledViewPool()
@@ -57,7 +58,12 @@ class ComposeItemAdapter @Inject constructor(private val colors: Colors) : QkAda
return QkViewHolder(view).apply { return QkViewHolder(view).apply {
view.setOnClickListener { view.setOnClickListener {
val item = getItem(adapterPosition) val item = getItem(adapterPosition)
itemSelected.onNext(item) clicks.onNext(item)
}
view.setOnLongClickListener {
val item = getItem(adapterPosition)
longClicks.onNext(item)
true
} }
} }
} }
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2019 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 com.moez.QKSMS.feature.compose.editing
enum class PhoneNumberAction {
CANCEL,
JUST_ONCE,
ALWAYS
}
@@ -0,0 +1,77 @@
/*
* Copyright (C) 2019 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 com.moez.QKSMS.feature.compose.editing
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.extensions.Optional
import com.moez.QKSMS.model.PhoneNumber
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.phone_number_list_item.view.*
import kotlinx.android.synthetic.main.radio_preference_view.view.*
import javax.inject.Inject
class PhoneNumberPickerAdapter @Inject constructor(
private val context: Context
) : QkAdapter<PhoneNumber>() {
val selectedItemChanges: Subject<Optional<Long>> = BehaviorSubject.create()
private var selectedItem: Long? = null
set(value) {
data.indexOfFirst { number -> number.id == field }.takeIf { it != -1 }?.run(::notifyItemChanged)
field = value
data.indexOfFirst { number -> number.id == field }.takeIf { it != -1 }?.run(::notifyItemChanged)
selectedItemChanges.onNext(Optional(value))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.phone_number_list_item, parent, false)
return QkViewHolder(view).apply {
view.setOnClickListener {
val phoneNumber = getItem(adapterPosition)
selectedItem = phoneNumber.id
}
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val phoneNumber = getItem(position)
val view = holder.itemView
view.number.radioButton.isChecked = phoneNumber.id == selectedItem
view.number.titleView.text = phoneNumber.address
view.number.summaryView.text = when (phoneNumber.isDefault) {
true -> context.getString(R.string.compose_number_picker_default, phoneNumber.type)
false -> phoneNumber.type
}
}
override fun onDatasetChanged() {
super.onDatasetChanged()
selectedItem = data.find { number -> number.isDefault }?.id ?: data.firstOrNull()?.id
}
}
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 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/>.
-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.moez.QKSMS.common.widget.RadioPreferenceView
android:id="@+id/number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:summary="Mobile"
tools:title="(123) 456-7890" />
</FrameLayout>
@@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 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/>.
-->
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:orientation="vertical">
<com.moez.QKSMS.common.widget.QkTextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginTop="16dp"
android:layout_marginRight="24dp"
android:textColor="?android:attr/textColorPrimary"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintTop_toTopOf="parent"
app:textSize="dialog"
tools:text="Choose a phone number"
tools:visibility="visible" />
<com.moez.QKSMS.common.widget.QkTextView
android:id="@+id/subtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginTop="2dp"
android:layout_marginRight="24dp"
android:textColor="?android:attr/textColorPrimary"
android:visibility="gone"
app:layout_constraintTop_toBottomOf="@id/title"
app:textSize="primary"
tools:text="Moez Bhatti"
tools:visibility="visible" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:visibility="gone"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintTop_toBottomOf="@id/subtitle"
tools:itemCount="2"
tools:listitem="@layout/phone_number_list_item"
tools:visibility="visible" />
<com.moez.QKSMS.common.widget.QkTextView
android:id="@+id/positiveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="?attr/selectableItemBackground"
android:padding="16dp"
android:textColor="?android:attr/textColorSecondary"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/list"
app:layout_goneMarginRight="8dp"
app:textSize="secondary"
tools:text="Always"
tools:visibility="visible" />
<com.moez.QKSMS.common.widget.QkTextView
android:id="@+id/negativeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="?attr/selectableItemBackground"
android:padding="16dp"
android:textColor="?android:attr/textColorSecondary"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintEnd_toStartOf="@id/positiveButton"
app:layout_constraintTop_toBottomOf="@id/list"
app:textSize="secondary"
tools:text="Just once"
tools:visibility="visible" />
</androidx.constraintlayout.widget.ConstraintLayout>
@@ -98,6 +98,10 @@
<item>Delete</item> <item>Delete</item>
</string-array> </string-array>
<string name="compose_number_picker_title">Choose a phone number</string>
<string name="compose_number_picker_default">%s ∙ Default</string>
<string name="compose_number_picker_once">Just once</string>
<string name="compose_number_picker_always">Always</string>
<string name="compose_title_selected">%d selected</string> <string name="compose_title_selected">%d selected</string>
<string name="compose_subtitle_results">%1$d of %2$d results</string> <string name="compose_subtitle_results">%1$d of %2$d results</string>
<string name="compose_send_group_title">Send as group message</string> <string name="compose_send_group_title">Send as group message</string>