rebased to latest master

This commit is contained in:
gavine99
2025-02-17 19:10:59 +11:00
parent 0f6c2fb694
commit 94019f5e7a
18 changed files with 1220 additions and 131 deletions
@@ -25,8 +25,10 @@ import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.ContentValues
import android.content.Intent
import android.content.res.ColorStateList
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import android.provider.ContactsContract
import android.provider.MediaStore
import android.speech.RecognizerIntent
@@ -39,6 +41,9 @@ import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import android.view.View.OnTouchListener
import android.widget.SeekBar
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
@@ -52,6 +57,7 @@ import com.google.android.material.snackbar.Snackbar
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.common.QkMediaPlayer
import com.uber.autodispose.ObservableSubscribeProxy
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import dagger.android.AndroidInjection
@@ -67,6 +73,7 @@ import dev.octoshrimpy.quik.common.util.extensions.setBackgroundTint
import dev.octoshrimpy.quik.common.util.extensions.setTint
import dev.octoshrimpy.quik.common.util.extensions.setVisible
import dev.octoshrimpy.quik.common.util.extensions.showKeyboard
import dev.octoshrimpy.quik.common.widget.MicInputCloudView
import dev.octoshrimpy.quik.common.widget.QkEditText
import dev.octoshrimpy.quik.extensions.mapNotNull
import dev.octoshrimpy.quik.feature.compose.editing.ChipsAdapter
@@ -74,13 +81,23 @@ import dev.octoshrimpy.quik.feature.contacts.ContactsActivity
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Recipient
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.compose_activity.attach
import kotlinx.android.synthetic.main.compose_activity.attachAFileIcon
import kotlinx.android.synthetic.main.compose_activity.attachAFileLabel
import kotlinx.android.synthetic.main.compose_activity.attaching
import kotlinx.android.synthetic.main.compose_activity.attachingBackground
import kotlinx.android.synthetic.main.compose_activity.shadeBackground
import kotlinx.android.synthetic.main.compose_activity.audioMsgAbort
import kotlinx.android.synthetic.main.compose_activity.audioMsgAttach
import kotlinx.android.synthetic.main.compose_activity.audioMsgBackground
import kotlinx.android.synthetic.main.compose_activity.audioMsgPlayerBackground
import kotlinx.android.synthetic.main.compose_activity.audioMsgPlayerPlayPause
import kotlinx.android.synthetic.main.compose_activity.audioMsgPlayerSeekBar
import kotlinx.android.synthetic.main.compose_activity.audioMsgRecord
import kotlinx.android.synthetic.main.compose_activity.camera
import kotlinx.android.synthetic.main.compose_activity.cameraLabel
import kotlinx.android.synthetic.main.compose_activity.chips
@@ -96,7 +113,11 @@ import kotlinx.android.synthetic.main.compose_activity.message
import kotlinx.android.synthetic.main.compose_activity.messageList
import kotlinx.android.synthetic.main.compose_activity.messagesEmpty
import kotlinx.android.synthetic.main.compose_activity.noValidRecipients
import kotlinx.android.synthetic.main.compose_activity.parts
import kotlinx.android.synthetic.main.compose_activity.messageAttachments
import kotlinx.android.synthetic.main.compose_activity.attachAnAudioMessageIcon
import kotlinx.android.synthetic.main.compose_activity.attachAnAudioMessageLabel
import kotlinx.android.synthetic.main.compose_activity.audioMsgDuration
import kotlinx.android.synthetic.main.compose_activity.recordAudioMsg
import kotlinx.android.synthetic.main.compose_activity.schedule
import kotlinx.android.synthetic.main.compose_activity.scheduleLabel
import kotlinx.android.synthetic.main.compose_activity.scheduledCancel
@@ -118,12 +139,13 @@ import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class ComposeActivity : QkThemedActivity(), ComposeView {
@Inject lateinit var attachmentAdapter: AttachmentAdapter
@Inject lateinit var composeAttachmentAdapter: ComposeAttachmentAdapter
@Inject lateinit var chipsAdapter: ChipsAdapter
@Inject lateinit var dateFormatter: DateFormatter
@Inject lateinit var messageAdapter: MessagesAdapter
@@ -144,9 +166,9 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
override val cancelSendingIntent: Subject<Long> by lazy { messageAdapter.cancelSendingClicks }
override val sendNowIntent: Subject<Long> by lazy { messageAdapter.sendNowClicks }
override val resendIntent: Subject<Long> by lazy { messageAdapter.resendClicks }
override val attachmentDeletedIntent: Subject<Attachment> by lazy { attachmentAdapter.attachmentDeleted }
override val attachmentDeletedIntent: Subject<Attachment> by lazy { composeAttachmentAdapter.attachmentDeleted }
override val textChangedIntent by lazy { message.textChanges() }
override val attachIntent by lazy { Observable.merge(attach.clicks(), attachingBackground.clicks()) }
override val attachIntent by lazy { Observable.merge(attach.clicks(), shadeBackground.clicks()) }
override val cameraIntent by lazy { Observable.merge(camera.clicks(), cameraLabel.clicks()) }
override val attachImageFileIntent by lazy { Observable.merge(gallery.clicks(), galleryLabel.clicks()) }
override val attachAnyFileIntent by lazy { Observable.merge(attachAFileIcon.clicks(), attachAFileLabel.clicks()) }
@@ -164,11 +186,53 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
override val confirmDeleteIntent: Subject<List<Long>> = PublishSubject.create()
override val messageLinkAskIntent: Subject<Uri> by lazy { messageAdapter.messageLinkClicks }
override val speechRecogniserIntent by lazy { speechToTextIcon.clicks() }
override val shadeIntent by lazy { shadeBackground.clicks() }
override val recordAnAudioMessage by lazy {
Observable.merge(recordAudioMsg.clicks(),
attachAnAudioMessageIcon.clicks(),
attachAnAudioMessageLabel.clicks())
}
override val recordAudioAbort by lazy { audioMsgAbort.clicks() }
override val recordAudioAttach by lazy { audioMsgAttach.clicks() }
override val recordAudioPlayerPlayPause: Subject<QkMediaPlayer.PlayingState> = PublishSubject.create()
override val recordAudioPlayerConfigUI: Subject<QkMediaPlayer.PlayingState> = PublishSubject.create()
override val recordAudioPlayerVisible: Subject<Boolean> = PublishSubject.create()
override val recordAudioChronometer: Subject<Boolean> = PublishSubject.create()
override val recordAudioStartStop: Subject<MicInputCloudView.ViewState> = PublishSubject.create()
private var seekBarUpdater: Disposable? = null
private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory)[ComposeViewModel::class.java] }
private var cameraDestination: Uri? = null
private fun getSeekBarUpdater(): ObservableSubscribeProxy<Long> {
return Observable.interval(500, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.single())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(scope())
}
private val speechResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK)
return@registerForActivityResult
// check returned results are good
val match = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
if ((match === null) || (match.size < 1) || (match[0].isNullOrEmpty()))
return@registerForActivityResult
// get the edit text view
val message = findViewById<QkEditText>(R.id.message)
if (message === null)
return@registerForActivityResult
// populate message box with data returned by STT, set cursor to end, and focus
message.append(match[0])
message.setSelection(message.text.length)
message.requestFocus()
}
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
@@ -196,15 +260,24 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
message.supportsInputContent = true
theme
.doOnNext { loading.setTint(it.theme) }
.doOnNext { attach.setBackgroundTint(it.theme) }
.doOnNext { attach.setTint(it.textPrimary) }
.doOnNext { speechToTextIconBorder.setBackgroundTint(it.theme) }
.doOnNext { speechToTextIcon.setBackgroundTint(it.textPrimary) }
.doOnNext { speechToTextIcon.setTint(it.theme) }
.doOnNext { messageAdapter.theme = it }
.autoDisposable(scope())
.subscribe()
.doOnNext { loading.setTint(it.theme) }
.doOnNext { attach.setBackgroundTint(it.theme) }
.doOnNext { attach.setTint(it.textPrimary) }
.doOnNext { speechToTextIconBorder.setBackgroundTint(it.theme) }
.doOnNext { speechToTextIcon.setBackgroundTint(it.textPrimary) }
.doOnNext { speechToTextIcon.setTint(it.theme) }
.doOnNext { audioMsgRecord.setColor(it.theme) }
.doOnNext { audioMsgPlayerPlayPause.setTint(it.theme) }
.doOnNext {
audioMsgPlayerSeekBar.apply {
thumbTintList = ColorStateList.valueOf(it.theme)
progressBackgroundTintList = ColorStateList.valueOf(it.theme)
progressTintList = ColorStateList.valueOf(it.theme)
}
}
.doOnNext { messageAdapter.theme = it }
.autoDisposable(scope())
.subscribe()
// context menu registration for message parts
messagePartContextMenuRegistrar
@@ -236,6 +309,86 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
true
}
// start/stop audio message recording
audioMsgRecord.setOnClickListener {
recordAudioStartStop.onNext(audioMsgRecord.getState())
}
recordAudioChronometer
.subscribeOn(AndroidSchedulers.mainThread())
.distinctUntilChanged()
.autoDisposable(scope())
.subscribe {
if (it) {
audioMsgDuration.base = SystemClock.elapsedRealtime()
audioMsgDuration.start()
} else {
audioMsgDuration.stop()
}
}
// audio record playback play/pause button
audioMsgPlayerPlayPause.setOnClickListener {
recordAudioPlayerPlayPause.onNext(
audioMsgPlayerPlayPause.tag as QkMediaPlayer.PlayingState
)
}
recordAudioPlayerVisible
.subscribeOn(AndroidSchedulers.mainThread())
.distinctUntilChanged()
.autoDisposable(scope())
.subscribe {
audioMsgPlayerBackground.isVisible = it
recordAudioPlayerConfigUI.onNext(QkMediaPlayer.PlayingState.Stopped)
}
recordAudioPlayerConfigUI
.subscribeOn(AndroidSchedulers.mainThread())
.distinctUntilChanged()
.autoDisposable(scope())
.subscribe {
when (it) {
QkMediaPlayer.PlayingState.Playing -> {
audioMsgPlayerPlayPause.tag = QkMediaPlayer.PlayingState.Playing
QkMediaPlayer.start()
audioMsgPlayerPlayPause.setImageResource(R.drawable.exo_icon_pause)
seekBarUpdater = getSeekBarUpdater().subscribe {
audioMsgPlayerSeekBar.progress = QkMediaPlayer.currentPosition
audioMsgPlayerSeekBar.max = QkMediaPlayer.duration
}
audioMsgPlayerSeekBar.isEnabled = true
}
QkMediaPlayer.PlayingState.Paused -> {
audioMsgPlayerPlayPause.tag = QkMediaPlayer.PlayingState.Paused
QkMediaPlayer.pause()
audioMsgPlayerPlayPause.setImageResource(R.drawable.exo_icon_play)
seekBarUpdater?.dispose()
}
else -> {
audioMsgPlayerPlayPause.tag = QkMediaPlayer.PlayingState.Stopped
QkMediaPlayer.reset()
audioMsgPlayerPlayPause.setImageResource(R.drawable.exo_icon_play)
seekBarUpdater?.dispose()
audioMsgPlayerSeekBar.progress = 0
audioMsgPlayerSeekBar.isEnabled = false
}
}
}
// audio msg player seek bar handler
audioMsgPlayerSeekBar.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(p0: SeekBar?, progress: Int, fromUser: Boolean) {
// if seek was initiated by the user and this part is currently playing
if (fromUser)
QkMediaPlayer.seekTo(progress)
}
override fun onStartTrackingTouch(p0: SeekBar?) {}
override fun onStopTrackingTouch(p0: SeekBar?) {}
}
)
window.callback = ComposeWindowCallback(window.callback, this)
}
@@ -264,6 +417,8 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
// stop any playing audio
QkMediaPlayer.reset()
seekBarUpdater?.dispose()
}
@@ -321,12 +476,19 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
scheduledGroup.isVisible = state.scheduled != 0L
scheduledTime.text = dateFormatter.getScheduledTimestamp(state.scheduled)
parts.setVisible(state.attachments.isNotEmpty())
attachmentAdapter.data = state.attachments
messageAttachments.setVisible(state.attachments.isNotEmpty())
composeAttachmentAdapter.data = state.attachments
attach.animate().rotation(if (state.attaching) 135f else 0f).start()
attaching.isVisible = state.attaching
shadeBackground.visibility =
if (state.attaching || state.audioMsgRecording) View.VISIBLE
else View.GONE
// show or hide audio message recording panel and shade background
audioMsgBackground.isVisible = state.audioMsgRecording
counter.text = state.remaining
counter.setVisible(counter.text.isNotBlank())
@@ -334,8 +496,9 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
sim.contentDescription = getString(R.string.compose_sim_cd, state.subscription?.displayName)
simIndex.text = state.subscription?.simSlotIndex?.plus(1)?.toString()
send.isEnabled = state.canSend
send.imageAlpha = if (state.canSend) 255 else 128
// show either send or audio msg record button
send.visibility = if (state.canSend && !state.loading) View.VISIBLE else View.INVISIBLE
recordAudioMsg.visibility = if (state.canSend && !state.loading) View.INVISIBLE else View.VISIBLE
// if not in editing mode, and there are no non-me participants that can be sent to,
// hide controls that allow constructing a reply and inform user no valid recipients
@@ -418,6 +581,10 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
}
override fun requestRecordAudioPermission() {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), 0)
}
override fun requestSmsPermission() {
ActivityCompat.requestPermissions(this, arrayOf(
Manifest.permission.READ_SMS,
@@ -21,15 +21,12 @@ package dev.octoshrimpy.quik.feature.compose
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.ViewModel
import com.google.android.mms.ContentType
import dev.octoshrimpy.quik.injection.ViewModelKey
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Attachments
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import java.net.URLDecoder
import java.nio.charset.Charset
import javax.inject.Named
@Module
@@ -74,12 +71,12 @@ class ComposeActivityModule {
@Provides
@Named("attachments")
fun provideSharedAttachments(activity: ComposeActivity): Attachments {
fun provideSharedAttachments(activity: ComposeActivity): List<Attachment> {
val uris = mutableListOf<Uri>()
activity.intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run(uris::add)
activity.intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run(uris::addAll)
return Attachments(uris.mapNotNull { Attachment(activity, it) })
return uris.mapNotNull { Attachment(activity, it) }
}
@Provides
@@ -41,7 +41,7 @@ import kotlinx.android.synthetic.main.attachment_contact_list_item.*
import javax.inject.Inject
class AttachmentAdapter @Inject constructor(
class ComposeAttachmentAdapter @Inject constructor(
private val context: Context
) : QkAdapter<Attachment, QkViewHolder>() {
@@ -40,11 +40,12 @@ data class ComposeState(
val messages: Pair<Conversation, RealmResults<Message>>? = null,
val selectedMessages: Int = 0,
val scheduled: Long = 0,
val attachments: List<Attachment> = ArrayList(),
val attachments: List<Attachment> = listOf(),
val attaching: Boolean = false,
val scheduling: Boolean = false,
val remaining: String = "",
val subscription: SubscriptionInfoCompat? = null,
val canSend: Boolean = false,
val validRecipientNumbers: Int = 1,
val audioMsgRecording: Boolean = false,
)
@@ -23,7 +23,9 @@ import android.view.MenuItem
import android.view.View
import androidx.annotation.StringRes
import androidx.core.view.inputmethod.InputContentInfoCompat
import com.moez.QKSMS.common.QkMediaPlayer
import dev.octoshrimpy.quik.common.base.QkView
import dev.octoshrimpy.quik.common.widget.MicInputCloudView
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Recipient
import io.reactivex.Observable
@@ -75,6 +77,15 @@ interface ComposeView : QkView<ComposeState> {
val confirmDeleteIntent: Observable<List<Long>>
val messageLinkAskIntent: Observable<Uri>
val speechRecogniserIntent: Observable<*>
val shadeIntent: Observable<Unit>
val recordAnAudioMessage: Observable<Unit>
val recordAudioAbort: Observable<Unit>
val recordAudioAttach: Observable<Unit>
val recordAudioPlayerPlayPause: Observable<QkMediaPlayer.PlayingState>
val recordAudioPlayerConfigUI: Subject<QkMediaPlayer.PlayingState>
val recordAudioPlayerVisible: Subject<Boolean>
val recordAudioStartStop: Subject<MicInputCloudView.ViewState>
val recordAudioChronometer: Subject<Boolean>
fun clearSelection()
fun toggleSelectAll()
@@ -83,6 +94,7 @@ interface ComposeView : QkView<ComposeState> {
fun showMessageLinkAskDialog(uri: Uri)
fun requestDefaultSms()
fun requestStoragePermission()
fun requestRecordAudioPermission()
fun requestSmsPermission()
fun showContacts(sharing: Boolean, chips: List<Recipient>)
fun themeChanged()
@@ -18,11 +18,18 @@
*/
package dev.octoshrimpy.quik.feature.compose
import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioAttributes
import android.net.Uri
import android.os.Vibrator
import android.telephony.SmsMessage
import androidx.core.content.getSystemService
import androidx.core.net.toFile
import androidx.core.net.toUri
import com.moez.QKSMS.common.QkMediaPlayer
import com.moez.QKSMS.contentproviders.MmsPartProvider
import com.moez.QKSMS.manager.MediaRecorderManager
import dev.octoshrimpy.quik.R
import dev.octoshrimpy.quik.common.Navigator
import dev.octoshrimpy.quik.common.base.QkViewModel
@@ -45,7 +52,6 @@ import dev.octoshrimpy.quik.manager.ActiveConversationManager
import dev.octoshrimpy.quik.manager.BillingManager
import dev.octoshrimpy.quik.manager.PermissionManager
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Attachments
import dev.octoshrimpy.quik.model.Conversation
import dev.octoshrimpy.quik.model.Message
import dev.octoshrimpy.quik.model.Recipient
@@ -58,6 +64,7 @@ import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.tryOrNull
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import dev.octoshrimpy.quik.common.widget.MicInputCloudView
import dev.octoshrimpy.quik.common.widget.QkContextMenuRecyclerView
import dev.octoshrimpy.quik.extensions.isSmil
import dev.octoshrimpy.quik.interactor.SaveImage
@@ -72,7 +79,9 @@ import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import timber.log.Timber
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
@@ -81,7 +90,7 @@ class ComposeViewModel @Inject constructor(
@Named("threadId") private val threadId: Long,
@Named("addresses") private val addresses: List<String>,
@Named("text") private val sharedText: String,
@Named("attachments") private val sharedAttachments: Attachments,
@Named("attachments") private val sharedAttachments: List<Attachment>,
@Named("mode") private val mode: String,
private val contactRepo: ContactRepository,
private val context: Context,
@@ -108,7 +117,10 @@ class ComposeViewModel @Inject constructor(
query = query)
) {
private val attachments: Subject<List<Attachment>> = BehaviorSubject.createDefault(sharedAttachments)
companion object {
private const val AUDIO_FILE_PREFIX = "recorded-"
}
private val chipsReducer: Subject<(List<Recipient>) -> List<Recipient>> = PublishSubject.create()
private val conversation: Subject<Conversation> = BehaviorSubject.create()
private val messages: Subject<List<Message>> = BehaviorSubject.create()
@@ -119,6 +131,9 @@ class ComposeViewModel @Inject constructor(
private var shouldShowContacts = threadId == 0L && addresses.isEmpty()
init {
// set shared attachments into state, if any
newState { copy(attachments = sharedAttachments) }
val initialConversation = threadId.takeIf { it != 0L }
?.let(conversationRepo::getConversationAsync)
?.asObservable()
@@ -199,9 +214,6 @@ class ComposeViewModel @Inject constructor(
.distinctUntilChanged()
.subscribe { enabled -> newState { copy(sendAsGroup = enabled) } }
disposables += attachments
.subscribe { attachments -> newState { copy(attachments = attachments) } }
disposables += conversation
.map { conversation -> conversation.id }
.distinctUntilChanged()
@@ -253,10 +265,11 @@ class ComposeViewModel @Inject constructor(
newState { copy(scheduling = true) }
}
@SuppressLint("StringFormatInvalid")
override fun bindView(view: ComposeView) {
super.bindView(view)
val sharing = sharedText.isNotEmpty() || sharedAttachments.isNotEmpty()
val sharing = (sharedText.isNotEmpty() || sharedAttachments.isNotEmpty())
if (shouldShowContacts) {
shouldShowContacts = false
view.showContacts(sharing, selectedChips.blockingFirst())
@@ -387,8 +400,10 @@ class ComposeViewModel @Inject constructor(
.filter { it == R.id.forward }
.withLatestFrom(view.messagesSelectedIntent) { _, messages ->
messages?.firstOrNull()?.let { messageRepo.getMessage(it) }?.let { message ->
val attachments = message.parts.filter { !it.isSmil() }.mapNotNull { it.getUri() }
navigator.showCompose(message.getText(), attachments)
navigator.showCompose(
message.getText(),
message.parts.filter { !it.isSmil() }.mapNotNull { it.getUri() }
)
}
}
.autoDisposable(view.scope())
@@ -648,15 +663,16 @@ class ComposeViewModel @Inject constructor(
.autoDisposable(view.scope())
.subscribe { view.requestDatePicker() }
// a file, photo or otherwise, was picked by the user
// an attachment was picked by the user
Observable.merge(
view.attachAnyFileSelectedIntent.map { uri -> Attachment(context, uri) },
view.inputContentIntent.map { inputContent -> Attachment(context, inputContent = inputContent) }
)
.withLatestFrom(attachments) { attachment, attachments -> attachments + attachment }
.doOnNext(attachments::onNext)
.autoDisposable(view.scope())
.subscribe { newState { copy(attaching = false) } }
.subscribe {
newState { copy(attachments = attachments + it, attaching = false) }
}
// Set the scheduled time
view.scheduleSelectedIntent
.filter { scheduled ->
@@ -675,20 +691,28 @@ class ComposeViewModel @Inject constructor(
// Contact was selected for attachment
view.contactSelectedIntent
.map { uri -> Attachment(context, uri) }
.withLatestFrom(attachments) { attachment, attachments -> attachments + attachment }
.subscribeOn(Schedulers.io())
.autoDisposable(view.scope())
.subscribe(attachments::onNext) { error ->
.subscribe(
{
newState {
copy(attachments = attachments + Attachment(context, uri = it))
}
}
) { error ->
context.makeToast(R.string.compose_contact_error)
Timber.w(error)
}
// Detach a photo
// Detach an attachment
view.attachmentDeletedIntent
.withLatestFrom(attachments) { bitmap, attachments -> attachments.filter { it !== bitmap } }
.autoDisposable(view.scope())
.subscribe { attachments.onNext(it) }
.subscribe {
newState { copy(attachments = attachments - it) }
// if the attachment is backed by a local file, delete the file
it.removeCacheFile()
}
conversation
.map { conversation -> conversation.draft }
@@ -707,14 +731,17 @@ class ComposeViewModel @Inject constructor(
}
}
// Enable the send button when there is text input into the new message body or there's
// an attachment, disable otherwise
Observables
.combineLatest(view.textChangedIntent, attachments) { text, attachments ->
text.isNotBlank() || attachments.isNotEmpty()
}
.autoDisposable(view.scope())
.subscribe { canSend -> newState { copy(canSend = canSend) } }
// set canSend state depending on if there is text input or an attachment
Observables.combineLatest(
view.textChangedIntent, // input message text changed
state
.distinctUntilChanged { state -> state.attachments } // attachments changed
.map { it.attachments.size } // number of attachments
)
.autoDisposable(view.scope())
.subscribe {
newState { copy(canSend = (it.first.isNotBlank() || (it.second > 0))) }
}
// Show the remaining character counter when necessary
view.textChangedIntent
@@ -766,11 +793,140 @@ class ComposeViewModel @Inject constructor(
.autoDisposable(view.scope())
.subscribe { view.startSpeechRecognition() }
// shade clicked
view.shadeIntent
.autoDisposable(view.scope())
.subscribe { newState { copy(attaching = false) } }
// starting or stopping (change state) of audio message recording
state
.distinctUntilChanged { state -> state.audioMsgRecording }
.skip(1) // skip initial value
.autoDisposable(view.scope())
.subscribe {
// stop any audio playback (ie from mms attachment or audio recorder)
QkMediaPlayer.stop()
// if leaving audio recording mode
if (!it.audioMsgRecording) {
// ensure recording stopped and delete any recording file
safeDeleteLocalFile(MediaRecorderManager.stopRecording())
view.recordAudioChronometer.onNext(false) // stop chronometer
}
}
// start recording an audio message
view.recordAnAudioMessage
.autoDisposable(view.scope())
.subscribe {
view.recordAudioPlayerVisible.onNext(false) // hide audio player
// check have permissions to record audio
if (permissionManager.hasRecordAudio().also {
if (!it) view.requestRecordAudioPermission()
}) {
newState { copy( attaching = false, audioMsgRecording = true) }
view.recordAudioChronometer.onNext(true) // start chronometer
MediaRecorderManager.startRecording(context)
}
}
// abort recording audio message button
view.recordAudioAbort
.observeOn(Schedulers.io())
.autoDisposable(view.scope())
.subscribe { newState { copy( audioMsgRecording = false) } }
// main record/stop recording audio message button
view.recordAudioStartStop
.autoDisposable(view.scope())
.subscribe {
if (it == MicInputCloudView.ViewState.PAUSED_STATE) {
view.recordAudioChronometer.onNext(false) // stop chronometer
MediaRecorderManager.stopRecording()
view.recordAudioPlayerVisible.onNext(true) // show audio player
} else { // state = start recording
// delete old recording file
safeDeleteLocalFile(MediaRecorderManager.uri)
view.recordAudioPlayerVisible.onNext(false) // hide audio player
view.recordAudioChronometer.onNext(true) // start chronometer
MediaRecorderManager.startRecording(context)
}
}
// attach recorded audio message button
view.recordAudioAttach
.autoDisposable(view.scope())
.subscribe {
MediaRecorderManager.stopRecording()
try {
// create new filename for recorded file
val newFile = File(
context.cacheDir,
"${AUDIO_FILE_PREFIX}${UUID.randomUUID()}${MediaRecorderManager.AUDIO_FILE_SUFFIX}"
)
// rename recorded file to new name
MediaRecorderManager.uri.toFile().renameTo(newFile)
// attach newly named file to message
newState {
copy(
audioMsgRecording = false,
attachments = attachments + Attachment(context, newFile.toUri())
)
}
}
catch (e: Exception) { /* nothing */ }
}
// audio recording player play/pause button
view.recordAudioPlayerPlayPause
.autoDisposable(view.scope())
.subscribe {
when (it) {
QkMediaPlayer.PlayingState.Paused ->
view.recordAudioPlayerConfigUI.onNext(
QkMediaPlayer.PlayingState.Playing
)
QkMediaPlayer.PlayingState.Playing ->
view.recordAudioPlayerConfigUI.onNext(
QkMediaPlayer.PlayingState.Paused
)
else -> {
if (MediaRecorderManager.uri != Uri.EMPTY) {
QkMediaPlayer.setOnPreparedListener {
view.recordAudioPlayerConfigUI.onNext(
QkMediaPlayer.PlayingState.Playing
)
}
QkMediaPlayer.setOnCompletionListener {
view.recordAudioPlayerConfigUI.onNext(
QkMediaPlayer.PlayingState.Stopped
)
}
// start the media player play sequence
QkMediaPlayer.setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
)
QkMediaPlayer.setDataSource(context, MediaRecorderManager.uri)
QkMediaPlayer.prepareAsync()
}
}
}
}
// Send a message when the send button is clicked, and disable editing mode if it's enabled
view.sendIntent
.withLatestFrom(view.textChangedIntent) { _, body -> body.toString() }
.withLatestFrom(state, attachments, conversation, selectedChips) { body, state, attachments,
conversation, chips ->
.withLatestFrom(state, conversation, selectedChips) { body, state, conversation, chips ->
if (!permissionManager.isDefaultSms()) {
view.requestDefaultSms()
return@withLatestFrom
@@ -804,7 +960,7 @@ class ComposeViewModel @Inject constructor(
// Scheduling a message
state.scheduled != 0L -> {
newState { copy(scheduled = 0) }
val uris = attachments.map { it.uri.toString() }
val uris = state.attachments.map { it.uri.toString() }
val params = AddScheduledMessage
.Params(state.scheduled, subId, addresses, sendAsGroup, body, uris)
addScheduledMessage.execute(params)
@@ -814,19 +970,19 @@ class ComposeViewModel @Inject constructor(
// Sending a group message
sendAsGroup -> {
sendMessage.execute(SendMessage
.Params(subId, conversation.id, addresses, body, attachments, delay))
.Params(subId, conversation.id, addresses, body, state.attachments, delay))
}
// Sending a message to an existing conversation with one recipient
conversation.recipients.size == 1 -> {
val address = conversation.recipients.map { it.address }
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, attachments, delay))
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, state.attachments, delay))
}
// Create a new conversation with one address
addresses.size == 1 -> {
sendMessage.execute(SendMessage
.Params(subId, threadId, addresses, body, attachments, delay))
.Params(subId, threadId, addresses, body, state.attachments, delay))
}
// Send a message to multiple addresses
@@ -838,13 +994,14 @@ class ComposeViewModel @Inject constructor(
val address = listOf(conversationRepo
.getConversation(threadId)?.recipients?.firstOrNull()?.address ?: addr)
sendMessage.execute(SendMessage
.Params(subId, threadId, address, body, attachments, delay))
.Params(subId, threadId, address, body, state.attachments, delay))
}
}
}
// configure for new message
view.setDraft("")
this.attachments.onNext(ArrayList())
newState { copy(attachments = listOf()) }
if (state.editingMode) {
newState { copy(editingMode = false, hasError = !sendAsGroup) }
@@ -880,6 +1037,28 @@ class ComposeViewModel @Inject constructor(
.autoDisposable(view.scope())
.subscribe { view.clearSelection() }
// when activity changes visibility, delete old recording cache files in background thread
// generally there won't be any, but under some circumstances some can be left behind
view.activityVisibleIntent
.subscribeOn(Schedulers.io())
.autoDisposable(view.scope())
.subscribe {
context.cacheDir.listFiles()?.forEach {
if (it.isFile &&
it.name.startsWith(AUDIO_FILE_PREFIX) &&
it.name.endsWith(MediaRecorderManager.AUDIO_FILE_SUFFIX))
safeDeleteLocalFile(it.toUri())
}
}
}
private fun safeDeleteLocalFile(uri: Uri): Boolean {
return try {
if (uri == Uri.EMPTY)
false
uri.toFile().delete()
}
catch (e: Exception) { false }
}
}