add delay send mms. add group send to individual recipients - sms and mms. add immediate show messages in convo, not wait for sent. new qktransaction that replaces android/smsmms transaction with mods for quik. lots of code cleanups and removing superfluous code. some bug fixes.

This commit is contained in:
gavine99
2025-04-10 16:59:35 +10:00
parent 6f70c8e932
commit 2810b56cd0
375 changed files with 20297 additions and 3161 deletions
@@ -21,6 +21,7 @@ package com.moez.QKSMS.contentproviders
import android.content.ContentProvider
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
@@ -55,21 +56,21 @@ class MmsPartProvider : ContentProvider() {
.encodedPath("part/$partId")
.build()
}
fun getUriForMmsPartId(partId: Long, partName: String): Uri {
return Uri
.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority("dev.octoshrimpy.quik.mmspart")
.encodedPath("part/$partId/$partName")
.build()
}
}
override fun onCreate(): Boolean {
return true
}
fun getUriForMmsPartId(context: Context, partId: Long, partName: String): Uri {
return Uri
.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority("${context.packageName}.mmspart")
.encodedPath("part/$partId/$partName")
.build()
}
override fun query(
uri: Uri,
projection: Array<String>?,
@@ -0,0 +1,64 @@
/*
* Copyright (C) 2017 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 dev.octoshrimpy.quik.interactor
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import io.reactivex.Flowable
import timber.log.Timber
import javax.inject.Inject
class ActionDelayedMessage @Inject constructor(
private val conversationRepo: ConversationRepository,
private val messageRepo: MessageRepository
) : Interactor<ActionDelayedMessage.Params>() {
enum class Action {
Send,
Cancel
}
data class Params(val messageId: Long, val action: Action)
override fun buildObservable(params: Params): Flowable<*> =
Flowable.just(params).doOnNext {
val updateConversations = mutableListOf<Long>()
// cancel the timer before doing anything else
messageRepo.cancelDelayedSmsAlarm(params.messageId)
messageRepo.getUnmanagedMessage(params.messageId)?.let { message ->
when (params.action) {
Action.Cancel -> {
messageRepo.deleteMessages(listOf(message.id))
updateConversations.add(message.threadId)
}
Action.Send -> {
updateConversations.addAll(
messageRepo.sendMessage(message).map { it.threadId }
)
}
}
conversationRepo.updateConversations(updateConversations)
} ?:let { Timber.e("couldn't find message id ${params.messageId}") }
}
}
@@ -21,13 +21,13 @@ package dev.octoshrimpy.quik.interactor
import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import androidx.core.net.toUri
import dev.octoshrimpy.quik.extensions.getName
import dev.octoshrimpy.quik.extensions.mapNotNull
import dev.octoshrimpy.quik.extensions.getResourceBytes
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import dev.octoshrimpy.quik.util.Constants
import dev.octoshrimpy.quik.util.FileUtils
import io.reactivex.Flowable
import io.realm.RealmList
import java.io.File
import java.util.UUID
import javax.inject.Inject
@@ -36,61 +36,53 @@ class AddScheduledMessage @Inject constructor(
private val updateScheduledMessageAlarms: UpdateScheduledMessageAlarms,
private val context: Context,
) : Interactor<AddScheduledMessage.Params>() {
data class Params(
val date: Long,
val subId: Int,
val recipients: List<String>,
val sendAsGroup: Boolean,
val body: String,
val attachments: List<String>
val attachments: List<Uri>
)
@SuppressLint("Range")
override fun buildObservable(params: Params): Flowable<*> {
// have to 3-step save scheduled message
return Flowable.just(params)
.map { // step 1 - save, as-is, to db to get primary key id
.map { // step 1 - save, without attachments, to db to get primary key id which is
// needed for building the save file location dir name in step 2
scheduledMessageRepo.saveScheduledMessage(
it.date, it.subId, it.recipients, it.sendAsGroup, it.body, it.attachments
it.date, it.subId, it.recipients, it.sendAsGroup, it.body, listOf()
)
}
.map { scheduledMessageDb ->
.map { scheduledMessage ->
// step 2 - copy attachments to app local storage
scheduledMessageDb.attachments = RealmList(
*scheduledMessageDb.attachments.mapNotNull {
val inUri = Uri.parse(it)
scheduledMessage.attachments = RealmList(
*params.attachments.map { attachmentUri ->
try {
// get filename of input uri or use random uuid on fail to get
val filename = inUri.getName(context) ?: UUID.randomUUID()
val filename = attachmentUri.getName(context) ?: UUID.randomUUID()
// copy attachment data to app local dir - first, create dir
val localFile = File(
context.filesDir,
"scheduled-${scheduledMessageDb.id}/${UUID.randomUUID()}/${filename}"
val (localUri, e) = FileUtils.createAndWrite(
context,
FileUtils.Location.Files, // files dir so not deleted if app cache wiped by user
"${Constants.SCHEDULED_MESSAGE_FILE_PREFIX}-${scheduledMessage.id}/" +
"${UUID.randomUUID()}/${filename}",
"",
attachmentUri.getResourceBytes(context)
)
// create directory tree in app local storage
localFile.parentFile?.mkdirs()
val localUri = localFile.toUri()
// copy attachment resource data to local file
context.contentResolver.openOutputStream(localUri, "w")
?.use { outputStream ->
context.contentResolver.openInputStream(inUri)
?.use { it.copyTo(outputStream, 4096) }
}
if (e is Exception)
throw e
localUri.toString()
} catch (e: Exception) {
it // on any error, use original uri string
attachmentUri.toString() // on any error, use original uri string
}
}.toTypedArray()
)
// step 3 - update scheduled message with new attachment uris
scheduledMessageRepo.updateScheduledMessage(scheduledMessageDb)
scheduledMessageRepo.updateScheduledMessage(scheduledMessage)
}
.flatMap { updateScheduledMessageAlarms.buildObservable(Unit) }
}
@@ -35,9 +35,13 @@ class DeleteMessages @Inject constructor(
override fun buildObservable(params: Params): Flowable<*> {
return Flowable.just(params.messageIds)
.doOnNext { messageIds -> messageRepo.deleteMessages(messageIds) } // Delete the messages
.doOnNext { conversationRepo.updateConversations(params.threadId) } // Update the conversation
.doOnNext { notificationManager.update(params.threadId) }
.doOnNext { messageIds ->
messageRepo.deleteMessages(messageIds)
conversationRepo.updateConversations(listOf(params.threadId))
notificationManager.update(params.threadId)
}
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
}
@@ -34,11 +34,10 @@ class DeleteOldMessages @Inject constructor(
override fun buildObservable(params: Unit): Flowable<*> = Flowable.fromCallable {
val maxAge = prefs.autoDelete.get().takeIf { it > 0 } ?: return@fromCallable
val counts = messageRepo.getOldMessageCounts(maxAge)
val threadIds = counts.keys.toLongArray()
Timber.d("Deleting ${counts.values.sum()} old messages from ${threadIds.size} conversations")
Timber.d("Deleting ${counts.values.sum()} old messages from ${counts.keys.size} conversations")
messageRepo.deleteOldMessages(maxAge)
conversationRepo.updateConversations(*threadIds)
conversationRepo.updateConversations(counts.keys)
}
}
@@ -18,7 +18,6 @@
*/
package dev.octoshrimpy.quik.interactor
import android.annotation.SuppressLint
import android.content.Context
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import io.reactivex.Flowable
@@ -30,21 +29,20 @@ class DeleteScheduledMessages @Inject constructor(
private val context: Context,
) : Interactor<List<Long>>() {
@SuppressLint("Range")
override fun buildObservable(scheduledMessageIds: List<Long>): Flowable<*> {
return Flowable.just(scheduledMessageIds)
.map {
override fun buildObservable(params: List<Long>): Flowable<*> {
return Flowable.just(Unit)
.doOnNext {
try {
// for each message id to delete
it.forEach {
params.forEach { scheduledMessageId ->
// recursively delete scheduled message top level dir
val topDir = File(context.filesDir, "scheduled-${it}")
val topDir = File(context.filesDir, "scheduled-${scheduledMessageId}")
topDir.exists() && topDir.deleteRecursively()
}
} catch (e: Exception) { /* nothing */ }
// delete the db entries
scheduledMessageRepo.deleteScheduledMessages(it)
scheduledMessageRepo.deleteScheduledMessages(params)
}
}
@@ -27,13 +27,13 @@ class MarkFailed @Inject constructor(
private val messageRepo: MessageRepository,
private val notificationManager: NotificationManager
) : Interactor<MarkFailed.Params>() {
data class Params(val messageId: Long, val resultCode: Int)
data class Params(val id: Long, val resultCode: Int)
override fun buildObservable(params: Params): Flowable<Unit> {
return Flowable.just(Unit)
.doOnNext { messageRepo.markFailed(params.id, params.resultCode) }
.doOnNext { notificationManager.notifyFailed(params.id) }
}
override fun buildObservable(params: Params): Flowable<Unit> =
Flowable.just(Unit)
.doOnNext {
if (messageRepo.markFailed(params.messageId, params.resultCode))
notificationManager.notifyFailed(params.messageId)
}
}
@@ -26,7 +26,7 @@ class MarkSeen @Inject constructor(private val messageRepo: MessageRepository) :
override fun buildObservable(params: Long): Flowable<Unit> {
return Flowable.just(Unit)
.doOnNext { messageRepo.markSeen(params) }
.doOnNext { messageRepo.markSeen(listOf(params)) }
}
}
@@ -22,11 +22,9 @@ import dev.octoshrimpy.quik.repository.MessageRepository
import io.reactivex.Flowable
import javax.inject.Inject
class MarkSent @Inject constructor(private val messageRepo: MessageRepository) : Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<Unit> {
return Flowable.just(Unit)
.doOnNext { messageRepo.markSent(params) }
}
class MarkSent @Inject constructor(private val messageRepo: MessageRepository)
: Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<Unit> =
Flowable.just(Unit).doOnNext { messageRepo.markSent(params) }
}
@@ -22,11 +22,11 @@ import dev.octoshrimpy.quik.repository.ConversationRepository
import io.reactivex.Flowable
import javax.inject.Inject
class MarkUnarchived @Inject constructor(private val conversationRepo: ConversationRepository) : Interactor<List<Long>>() {
class MarkUnarchived @Inject constructor(private val conversationRepo: ConversationRepository)
: Interactor<List<Long>>() {
override fun buildObservable(params: List<Long>): Flowable<*> {
return Flowable.just(params.toLongArray())
.doOnNext { threadIds -> conversationRepo.markUnarchived(*threadIds) }
return Flowable.just(params)
.doOnNext { threadIds -> conversationRepo.markUnarchived(threadIds) }
}
}
@@ -44,53 +44,57 @@ class ReceiveMms @Inject constructor(
override fun buildObservable(params: Uri): Flowable<*> {
return Flowable.just(params)
.mapNotNull(syncManager::syncMessage) // Sync the message
.doOnNext { message ->
// TODO: Ideally this is done when we're saving the MMS to ContentResolver
// This change can be made once we move the MMS storing code to the Data module
if (activeConversationManager.getActiveConversation() == message.threadId) {
.mapNotNull(syncManager::syncMessage) // Sync the message
.doOnNext { message ->
// TODO: Ideally this is done when we're saving the MMS to ContentResolver
// This change can be made once we move the MMS storing code to the Data module
if (activeConversationManager.getActiveConversation() == message.threadId) {
messageRepo.markRead(listOf(message.threadId))
}
}
.mapNotNull { message ->
// Because we use the smsmms library for receiving and storing MMS, we'll need
// to check if it should be blocked after we've pulled it into realm. If it
// turns out that it should be dropped, then delete it
// TODO Don't store blocked messages in the first place
val action = blockingClient.shouldBlock(message.address).blockingGet()
val shouldDrop = prefs.drop.get()
Timber.v("block=$action, drop=$shouldDrop")
if (action is BlockingClient.Action.Block && shouldDrop) {
messageRepo.deleteMessages(listOf(message.id))
return@mapNotNull null
}
when (action) {
is BlockingClient.Action.Block -> {
messageRepo.markRead(listOf(message.threadId))
conversationRepo.markBlocked(
listOf(message.threadId), prefs.blockingManager.get(), action.reason
)
}
is BlockingClient.Action.Unblock ->
conversationRepo.markUnblocked(message.threadId)
else -> Unit
}
.mapNotNull { message ->
// Because we use the smsmms library for receiving and storing MMS, we'll need
// to check if it should be blocked after we've pulled it into realm. If it
// turns out that it should be dropped, then delete it
// TODO Don't store blocked messages in the first place
val action = blockingClient.shouldBlock(message.address).blockingGet()
val shouldDrop = prefs.drop.get()
Timber.v("block=$action, drop=$shouldDrop")
if (action is BlockingClient.Action.Block && shouldDrop) {
messageRepo.deleteMessages(listOf(message.id))
return@mapNotNull null
}
when (action) {
is BlockingClient.Action.Block -> {
messageRepo.markRead(listOf(message.threadId))
conversationRepo.markBlocked(listOf(message.threadId), prefs.blockingManager.get(), action.reason)
}
is BlockingClient.Action.Unblock -> conversationRepo.markUnblocked(message.threadId)
else -> Unit
}
message
}
.doOnNext { message ->
conversationRepo.updateConversations(message.threadId) // Update the conversation
}
.mapNotNull { message ->
conversationRepo.getOrCreateConversation(message.threadId) // Map message to conversation
}
.filter { conversation -> !conversation.blocked } // Don't notify for blocked conversations
.doOnNext { conversation ->
// Unarchive conversation if necessary
if (conversation.archived) conversationRepo.markUnarchived(conversation.id)
}
.map { conversation -> conversation.id } // Map to the id because [delay] will put us on the wrong thread
.doOnNext(notificationManager::update) // Update the notification
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
message
}
.doOnNext { message ->
conversationRepo.updateConversations(listOf(message.threadId)) // Update the conversation
}
.mapNotNull { message ->
conversationRepo.getOrCreateConversation(message.threadId) // Map message to conversation
}
.filter { conversation -> !conversation.blocked } // Don't notify for blocked conversations
.doOnNext { conversation ->
// Unarchive conversation if necessary
if (conversation.archived)
conversationRepo.markUnarchived(listOf(conversation.id))
}
.map { conversation -> conversation.id } // Map to the id because [delay] will put us on the wrong thread
.doOnNext(notificationManager::update) // Update the notification
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
}
}
@@ -70,7 +70,7 @@ class ReceiveSms @Inject constructor(
}
// update and fetch conversation
conversationRepo.updateConversations(it.threadId)
conversationRepo.updateConversations(listOf(it.threadId))
conversationRepo.getOrCreateConversation(it.threadId)
}
.mapNotNull {
@@ -83,7 +83,7 @@ class ReceiveSms @Inject constructor(
// unarchive conversation if necessary
if (it.archived) {
Timber.v("conversation unarchived")
conversationRepo.markUnarchived(it.id)
conversationRepo.markUnarchived(listOf(it.id))
}
// update/create notification
@@ -1,41 +0,0 @@
/*
* Copyright (C) 2017 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 dev.octoshrimpy.quik.interactor
import dev.octoshrimpy.quik.extensions.mapNotNull
import dev.octoshrimpy.quik.model.Message
import dev.octoshrimpy.quik.repository.MessageRepository
import io.reactivex.Flowable
import javax.inject.Inject
class RetrySending @Inject constructor(private val messageRepo: MessageRepository) : Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<Message> {
return Flowable.just(params)
.doOnNext(messageRepo::markSending)
.mapNotNull(messageRepo::getMessage)
.doOnNext { message ->
when (message.isSms()) {
true -> messageRepo.sendSms(message)
false -> messageRepo.resendMms(message)
}
}
}
}
@@ -18,23 +18,15 @@
*/
package dev.octoshrimpy.quik.interactor
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import io.reactivex.Flowable
import javax.inject.Inject
class CancelDelayedMessage @Inject constructor(
private val conversationRepo: ConversationRepository,
class SendExistingMessage @Inject constructor(
private val messageRepo: MessageRepository
) : Interactor<CancelDelayedMessage.Params>() {
data class Params(val messageId: Long, val threadId: Long)
override fun buildObservable(params: Params): Flowable<*> {
return Flowable.just(Unit)
.doOnNext { messageRepo.cancelDelayedSms(params.messageId) }
.doOnNext { messageRepo.deleteMessages(listOf(params.messageId)) }
.doOnNext { conversationRepo.updateConversations(params.threadId) } // Update the conversation
}
) : Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<Long> =
Flowable.just(params)
.doOnNext { messageId -> messageRepo.sendMessage(messageId) }
}
@@ -18,53 +18,59 @@
*/
package dev.octoshrimpy.quik.interactor
import android.content.Context
import dev.octoshrimpy.quik.manager.ShortcutManager
import dev.octoshrimpy.quik.extensions.mapNotNull
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import io.reactivex.Flowable
import timber.log.Timber
import javax.inject.Inject
class SendMessage @Inject constructor(
private val context: Context,
class SendNewMessage @Inject constructor(
private val conversationRepo: ConversationRepository,
private val messageRepo: MessageRepository,
private val updateBadge: UpdateBadge,
private val shortcutManager: ShortcutManager
) : Interactor<SendMessage.Params>() {
) : Interactor<SendNewMessage.Params>() {
data class Params(
val subId: Int,
val threadId: Long,
val addresses: List<String>,
val addresses: Collection<String>,
val body: String,
val attachments: List<Attachment> = listOf(),
val sendAsGroup: Boolean,
val attachments: Collection<Attachment> = listOf(),
val delay: Int = 0
)
override fun buildObservable(params: Params): Flowable<*> = Flowable.just(Unit)
.filter { params.addresses.isNotEmpty() }
.doOnNext {
// If a threadId isn't provided, try to obtain one
val threadId = when (params.threadId) {
0L -> conversationRepo.getOrCreateConversation(params.addresses)?.id ?: 0
else -> params.threadId
.mapNotNull {
// if addresses are provided, prefer them over the thread id because from a user
// perspective it is more important that the intended recipients are messaged rather
// than that messages go to a thread id
when {
params.addresses.isNotEmpty() ->
conversationRepo.getOrCreateConversation(params.addresses)
(params.threadId > 0) ->
conversationRepo.getOrCreateConversation(params.threadId)
else -> null
}
?:let { Timber.e("unable to get or create a conversation record"); null }
}
.map { conversation ->
// send the message
messageRepo.sendNewMessages(params.subId, conversation.recipients.map { it.address },
params.body, params.attachments, params.sendAsGroup, params.delay)
}
.map { messages -> messages.map { it.threadId } }
.doOnNext { threadIds ->
conversationRepo.updateConversations(threadIds)
conversationRepo.markUnarchived(threadIds)
// if unable to find or create a conversation (and/or underlying threadId), fail
if (threadId == 0L)
return@doOnNext
params.apply {
messageRepo.sendMessage(subId, threadId, addresses, body, attachments, delay)
}
conversationRepo.updateConversations(threadId)
conversationRepo.markUnarchived(threadId)
shortcutManager.reportShortcutUsed(threadId)
threadIds.forEach { threadId -> shortcutManager.reportShortcutUsed(threadId) }
// delete attachment local files, if any, because they're saved to mms db by now
params.attachments.forEach { it.removeCacheFile() }
@@ -33,7 +33,7 @@ class SendScheduledMessage @Inject constructor(
private val context: Context,
private val scheduledMessageRepo: ScheduledMessageRepository,
private val deleteScheduledMessagesInteractor: DeleteScheduledMessages,
private val sendMessage: SendMessage
private val sendNewMessage: SendNewMessage
) : Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<*> {
@@ -49,9 +49,12 @@ class SendScheduledMessage @Inject constructor(
.map { message ->
val threadId = TelephonyCompat.getOrCreateThreadId(context, message.recipients)
val attachments = message.attachments.mapNotNull(Uri::parse).map { Attachment(context, it) }
SendMessage.Params(message.subId, threadId, message.recipients, message.body, attachments)
SendNewMessage.Params(
message.subId, threadId, message.recipients, message.body,
message.sendAsGroup, attachments
)
}
.flatMap(sendMessage::buildObservable)
.flatMap(sendNewMessage::buildObservable)
.doOnNext { deleteScheduledMessagesInteractor.execute(listOf(params)) }
}
@@ -18,9 +18,7 @@
*/
package dev.octoshrimpy.quik.interactor
import android.content.res.Resources
import com.moez.QKSMS.manager.SpeakManager
import dev.octoshrimpy.quik.domain.R
import dev.octoshrimpy.quik.extensions.mapNotNull
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
@@ -31,6 +29,7 @@ import javax.inject.Inject
class SpeakThreads @Inject constructor(
private val conversationRepo: ConversationRepository,
private val messageRepo: MessageRepository,
private val speakManager: SpeakManager
) : Interactor<List<Long>>() {
companion object {
@@ -42,8 +41,6 @@ class SpeakThreads @Inject constructor(
}
override fun buildObservable(threadIds: List<Long>): Flowable<*> {
val speakManager = SpeakManager()
if (threadIds.isEmpty())
return Single.just(0)
.doOnSubscribe { speakManager.startSpeakSession(noMessagesStr) }
@@ -54,9 +51,10 @@ class SpeakThreads @Inject constructor(
return Flowable.fromIterable(threadIds)
.doOnSubscribe { speakManager.startSpeakSession("threads:" + threadIds.sorted().joinToString()) }
.mapNotNull { threadId -> conversationRepo.getConversationAndLastSenderContactName(threadId) }
.map { conversationAndSender ->
if (speakManager.speakConversationLastSms(conversationAndSender))
messageRepo.markSeen(conversationAndSender.first!!.id)
.map { (conversation, sender) ->
if (speakManager.speakConversationLastSms(Pair(conversation, sender)) &&
conversation != null)
messageRepo.markSeen(listOf(conversation.id))
}
.doOnTerminate { speakManager.endSpeakSession() }
}
@@ -29,13 +29,17 @@ class SyncMessage @Inject constructor(
private val conversationRepo: ConversationRepository,
private val syncManager: SyncRepository,
private val updateBadge: UpdateBadge
) : Interactor<Uri>() {
) : Interactor<SyncMessage.Params>() {
override fun buildObservable(params: Uri): Flowable<*> {
data class Params(val uri: Uri, val messageId: Long = 0)
override fun buildObservable(params: Params): Flowable<*> {
return Flowable.just(params)
.mapNotNull { uri -> syncManager.syncMessage(uri) }
.doOnNext { message -> conversationRepo.updateConversations(message.threadId) }
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
.mapNotNull { syncManager.syncMessage(it.uri, it.messageId) }
.doOnNext {
message -> conversationRepo.updateConversations(listOf(message.threadId))
}
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
}
}
@@ -14,33 +14,24 @@ import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class SpeakManager() {
class SpeakManager @Inject constructor (private val context: Context) {
companion object {
// system TextToSpeech engine
private var staticTextToSpeech = AtomicReference<TextToSpeech>(null)
val lock = Any()
private var context: Context? = null
// currently speaking sessionId
private var currentSessionId: String? = null
// audio manager items for audio focus
private var audioManager: AudioManager? = null
private var audioFocusRequest: AudioFocusRequest? = null
fun setContext(inContext: Context) {
synchronized(lock) {
if (context !== null)
return
context = inContext
}
}
}
private var sessionId: String? = null
@@ -53,12 +44,9 @@ class SpeakManager() {
if (tts !== null)
return tts
// if context not set then the global engine can not be instantiated
if (context === null)
return null
val audioAttributes = AudioAttributes.Builder(). run {
setUsage(AudioAttributes.USAGE_ASSISTANT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
setUsage(AudioAttributes.USAGE_ASSISTANT)
setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
build()
}
@@ -70,7 +58,7 @@ class SpeakManager() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// init audio manager and audio focus request first time through only
localAudioManager =
context?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (localAudioManager === null)
return null
@@ -199,10 +187,9 @@ class SpeakManager() {
this.sessionId = sessionId
sessionStopped = if ((this.sessionId !== null) && (toggle) && (currentSessionId == sessionId)) {
true // do not output any speech in this session
} else
false
// do not output any speech in this session
sessionStopped =
(this.sessionId !== null) && (toggle) && (currentSessionId == sessionId)
// stop any current speech immediately
stopSpeaking()
@@ -212,7 +199,7 @@ class SpeakManager() {
sessionStopped = true
}
fun stopSpeaking() {
private fun stopSpeaking() {
// get or init system TextToSpeech engine
val tts = getSystemTtsEngine()
if (tts === null)
@@ -21,7 +21,7 @@ package dev.octoshrimpy.quik.manager
interface WidgetManager {
companion object {
const val ACTION_NOTIFY_DATASET_CHANGED = "dev.octoshrimpy.quik.intent.action.ACTION_NOTIFY_DATASET_CHANGED"
const val ACTION_NOTIFY_DATASET_CHANGED = "action.ACTION_NOTIFY_DATASET_CHANGED"
}
fun sendDatasetChanged()
@@ -22,7 +22,6 @@ import android.database.Cursor
import android.provider.Telephony.*
import dev.octoshrimpy.quik.model.Message
import timber.log.Timber
import java.util.*
interface CursorToMessage : Mapper<Pair<Cursor, CursorToMessage.MessageColumns>, Message> {
@@ -55,13 +54,13 @@ interface CursorToMessage : Mapper<Pair<Cursor, CursorToMessage.MessageColumns>,
val mmsMessageBox by lazy { getColumnIndex(Mms.MESSAGE_BOX) }
val mmsDeliveryReport by lazy { getColumnIndex(Mms.DELIVERY_REPORT) }
val mmsReadReport by lazy { getColumnIndex(Mms.READ_REPORT) }
val mmsErrorType by lazy { getColumnIndex(MmsSms.PendingMessages.ERROR_TYPE) }
// val mmsErrorType by lazy { getColumnIndex(MmsSms.PendingMessages.ERROR_TYPE) }
val mmsStatus by lazy { getColumnIndex(Mms.STATUS) }
private fun getColumnIndex(columnsName: String) = try {
cursor.getColumnIndexOrThrow(columnsName)
} catch (e: Exception) {
Timber.e("Couldn't find column \'$columnsName\' in ${Arrays.toString(cursor.columnNames)}")
Timber.e("Couldn't find column \'$columnsName\' in ${cursor.columnNames.contentToString()}")
-1
}
}
@@ -18,7 +18,6 @@
*/
package dev.octoshrimpy.quik.model
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
@@ -36,7 +35,6 @@ import dev.octoshrimpy.quik.extensions.isImage
import dev.octoshrimpy.quik.extensions.isVCard
@SuppressLint("Range")
class Attachment (
context: Context,
var uri: Uri = Uri.EMPTY,
@@ -35,7 +35,9 @@ open class Conversation(
var blockingClient: Int? = null,
var blockReason: String? = null,
var name: String = "" // For group chats, the user is allowed to set a custom title for the conversation
var name: String = "", // custom title
var sendAsGroup: Boolean = false,
) : RealmObject() {
val date: Long get() = lastMessage?.date ?: 0
@@ -28,6 +28,10 @@ import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
open class Message : RealmObject() {
companion object {
const val TYPE_SMS = "sms"
const val TYPE_MMS = "mms"
}
enum class AttachmentType { TEXT, IMAGE, VIDEO, AUDIO, SLIDESHOW, NOT_LOADED }
@@ -73,14 +77,19 @@ open class Message : RealmObject() {
var textContentType: String = ""
var parts: RealmList<MmsPart> = RealmList()
var sendAsGroup: Boolean = false
fun getUri(): Uri {
val baseUri = if (isMms()) Mms.CONTENT_URI else Sms.CONTENT_URI
return ContentUris.withAppendedId(baseUri, contentId)
if (contentId == 0L)
return Uri.EMPTY
return ContentUris.withAppendedId(
if (isMms()) Mms.CONTENT_URI else Sms.CONTENT_URI, contentId
)
}
fun isMms(): Boolean = type == "mms"
fun isMms(): Boolean = type == TYPE_MMS
fun isSms(): Boolean = type == "sms"
fun isSms(): Boolean = type == TYPE_SMS
fun isMe(): Boolean {
val isIncomingMms = isMms() && (boxId == Mms.MESSAGE_BOX_INBOX || boxId == Mms.MESSAGE_BOX_ALL)
@@ -90,7 +99,7 @@ open class Message : RealmObject() {
}
fun isOutgoingMessage(): Boolean {
val isOutgoingMms = isMms() && boxId == Mms.MESSAGE_BOX_OUTBOX
val isOutgoingMms = isMms() && (boxId == Mms.MESSAGE_BOX_OUTBOX)
val isOutgoingSms = isSms() && (boxId == Sms.MESSAGE_TYPE_FAILED
|| boxId == Sms.MESSAGE_TYPE_OUTBOX
|| boxId == Sms.MESSAGE_TYPE_QUEUED)
@@ -98,9 +107,6 @@ open class Message : RealmObject() {
return isOutgoingMms || isOutgoingSms
}
/**
* Returns the text that should be copied to the clipboard
*/
fun getText(withSubject: Boolean = true): String {
val messageText = when {
isSms() -> body
@@ -139,10 +145,10 @@ open class Message : RealmObject() {
val sb = StringBuilder()
// Add subject
getCleansedSubject().takeIf { it.isNotEmpty() }?.run(sb::appendln)
getCleansedSubject().takeIf { it.isNotEmpty() }?.run(sb::appendLine)
// Add parts
parts.mapNotNull { it.getSummary() }.forEach { summary -> sb.appendln(summary) }
parts.mapNotNull { it.getSummary() }.forEach { summary -> sb.appendLine(summary) }
sb.toString().trim()
}
@@ -19,10 +19,8 @@
package dev.octoshrimpy.quik.model
import android.content.ContentResolver
import android.content.ContentResolver.MimeTypeInfo
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.core.net.toUri
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.Index
@@ -50,9 +48,12 @@ open class MmsPart : RealmObject() {
.build()
fun getBestFilename(): String =
if (File(name).extension.isNotEmpty()) name ?: "unknown"
else "$name." + (MimeTypeMap.getSingleton().getExtensionFromMimeType(type)
?: type.substringAfter("/"))
if (name.isNullOrBlank()) "unknown"
else if (File(name!!).extension.isNotEmpty()) name!!
else "$name" +
if (type.isBlank()) ""
else ".${MimeTypeMap.getSingleton().getExtensionFromMimeType(type)
?: type.substringAfter("/")}"
fun getSummary(): String? = when {
type == "application/smil" -> null
@@ -31,9 +31,6 @@ interface ConversationRepository {
fun getConversationsSnapshot(unreadAtTop: Boolean): List<Conversation>
/**
* Returns the top conversations that were active in the last week
*/
fun getTopConversations(): List<Conversation>
fun setConversationName(id: Long, name: String): Completable
@@ -48,15 +45,14 @@ interface ConversationRepository {
fun getConversation(threadId: Long): Conversation?
fun updateSendAsGroup(threadId: Long, sendAsGroup: Boolean): Unit?
fun getUnseenIds(archived: Boolean = false): List<Long>
fun getUnreadIds(archived: Boolean = false): List<Long>
fun getConversationAndLastSenderContactName(threadId: Long): Pair<Conversation?, String?>?
/**
* Returns all conversations with an id in [threadIds]
*/
fun getConversations(vararg threadIds: Long): RealmResults<Conversation>
fun getUnmanagedConversations(): Observable<List<Conversation>>
@@ -67,26 +63,27 @@ interface ConversationRepository {
fun getRecipient(recipientId: Long): Recipient?
fun getConversation(recipient: String): Conversation?
fun getOrCreateConversation(threadId: Long, sendAsGroup: Boolean = false): Conversation?
fun getConversation(recipients: Collection<String>): Conversation?
fun createConversation(threadId: Long, sendAsGroup: Boolean = false): Conversation?
fun getOrCreateConversation(threadId: Long): Conversation?
fun getConversation(addresses: Collection<String>): Conversation?
fun getOrCreateConversation(address: String): Conversation?
fun getOrCreateConversation(
addresses: Collection<String>, sendAsGroup: Boolean = false
): Conversation?
fun getOrCreateConversation(addresses: Collection<String>): Conversation?
fun createConversation(
addresses: Collection<String>, sendAsGroup: Boolean = false
): Conversation?
fun saveDraft(threadId: Long, draft: String)
/**
* Updates message-related fields in the conversation, like the date and snippet
*/
fun updateConversations(vararg threadIds: Long)
fun updateConversations(threadIds: Collection<Long>)
fun markArchived(vararg threadIds: Long)
fun markUnarchived(vararg threadIds: Long)
fun markUnarchived(threadIds: Collection<Long>)
fun markPinned(vararg threadIds: Long)
@@ -23,15 +23,17 @@ import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Message
import dev.octoshrimpy.quik.model.MmsPart
import io.realm.RealmResults
import java.io.File
interface MessageRepository {
fun getMessages(threadId: Long, query: String = ""): RealmResults<Message>
fun getMessagesSync(threadId: Long, query: String = ""): RealmResults<Message>
fun getMessage(id: Long): Message?
fun getMessage(messageId: Long): Message?
fun getUnmanagedMessage(messageId: Long): Message?
fun getMessages(messageIds: Collection<Long>): RealmResults<Message>
fun getMessageForPart(id: Long): Message?
@@ -45,74 +47,45 @@ interface MessageRepository {
fun savePart(id: Long): Uri?
/**
* Retrieves the list of messages which should be shown in the notification
* for a given conversation
*/
fun getUnreadUnseenMessages(threadId: Long): RealmResults<Message>
/**
* Retrieves the list of messages which should be shown in the quickreply popup
* for a given conversation
*/
fun getUnreadMessages(threadId: Long): RealmResults<Message>
fun markAllSeen(): Int
fun markSeen(threadId: Long): Int
fun markSeen(threadIds: Collection<Long>): Int
fun markRead(threadIds: Collection<Long>): Int
fun markUnread(threadIds: Collection<Long>): Int
fun sendMessage(
subId: Int,
threadId: Long,
addresses: Collection<String>,
body: String,
attachments: Collection<Attachment>,
delay: Int = 0
)
fun markSending(messageId: Long)
/**
* Attempts to send the SMS message. This can be called if the message has already been persisted
*/
fun sendSms(message: Message)
fun markSent(messageId: Long)
fun resendMms(message: Message)
fun markFailed(messageId: Long, resultCode: Int): Boolean
/**
* Attempts to cancel sending the message with the given id
*/
fun cancelDelayedSms(id: Long)
fun markDelivered(messageId: Long)
fun insertSentSms(subId: Int, threadId: Long, address: String, body: String, date: Long): Message
fun markDeliveryFailed(messageId: Long, resultCode: Int)
fun sendNewMessages(
subId: Int, toAddresses: Collection<String>, body: String,
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int = 0
): Collection<Message>
fun sendMessage(message: Message): Collection<Message>
fun sendMessage(messageId: Long): Collection<Message>
fun cancelDelayedSmsAlarm(messageId: Long)
fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long): Message
/**
* Marks the message as sending, in case we need to retry sending it
*/
fun markSending(id: Long)
fun markSent(id: Long)
fun markFailed(id: Long, resultCode: Int)
fun markDelivered(id: Long)
fun markDeliveryFailed(id: Long, resultCode: Int)
fun deleteMessages(messageIds: Collection<Long>)
/**
* Returns the number of messages older than [maxAgeDays] per conversation
*/
fun getOldMessageCounts(maxAgeDays: Int): Map<Long, Int>
/**
* Deletes all messages older than [maxAgeDays]
*/
fun deleteOldMessages(maxAgeDays: Int)
}
@@ -33,7 +33,7 @@ interface SyncRepository {
fun syncMessages()
fun syncMessage(uri: Uri): Message?
fun syncMessage(uri: Uri, messageId: Long = 0): Message?
fun syncContacts()
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2025
*
* This file is part of QUIK.
*
* QUIK 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.
*
* QUIK 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 QUIK. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.util
class Constants {
companion object {
const val SAVED_MESSAGE_TEXT_FILE_PREFIX = "QuikSmsText-"
const val SCHEDULED_MESSAGE_FILE_PREFIX = "scheduled-"
const val DELAY_CANCELLED_CACHED_ATTACHMENTS_FILE_PREFIX = "delaycancelled-"
}
}
@@ -0,0 +1,168 @@
/*
* Copyright (C) 2025
*
* This file is part of QUIK.
*
* QUIK 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.
*
* QUIK 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 QUIK. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.util
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.contentValuesOf
import androidx.core.net.toFile
import dev.octoshrimpy.quik.extensions.isEmpty
import java.io.File
object FileUtils {
enum class Location {
Downloads,
ExternalCache,
Cache,
Files,
Obb,
CodeCache,
NoBackup,
}
fun create(
location: Location,
context: Context,
filename: String,
mimeType: String
) =
if (location == Location.Downloads) createDownloadsFile(context, filename, mimeType)
else createLocation(location, context, filename)
private fun createDownloadsFile(
context: Context,
filename: String,
mimeType: String
): Pair<Uri, Exception?> =
try {
val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // use media store
context.contentResolver.insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
contentValuesOf(
MediaStore.MediaColumns.MIME_TYPE to mimeType,
MediaStore.MediaColumns.RELATIVE_PATH to
Environment.DIRECTORY_DOWNLOADS,
MediaStore.MediaColumns.DISPLAY_NAME to filename,
)
) ?: Uri.EMPTY
} else { // use direct access to 'external' dir
File(Environment.getExternalStorageDirectory(), filename).let {
if (tryOrNull { it.createNewFile() } == true) Uri.fromFile(it)
else Uri.EMPTY
}
}
if (uri.isEmpty())
throw Exception("Opening file returned an empty uri")
Pair(uri, null)
} catch (e: Exception) {
Pair(Uri.EMPTY, e)
}
private fun createLocation(
location: Location,
context: Context,
filename: String
): Pair<Uri, Exception?> =
try {
val uri = File(
when (location) {
Location.ExternalCache -> context.externalCacheDir
Location.Files -> context.filesDir
Location.Obb -> context.obbDir
Location.CodeCache -> context.codeCacheDir
Location.NoBackup -> context.noBackupFilesDir
else -> context.cacheDir
},
filename
).let {
if (tryOrNull {
it.parentFile?.mkdirs()
it.createNewFile()
} == true) Uri.fromFile(it)
else Uri.EMPTY
}
if (uri.isEmpty())
throw Exception("Opening file returned an empty uri")
Pair(uri, null)
} catch (e: Exception) {
Pair(Uri.EMPTY, e)
}
private fun writeBytes(
context: Context,
uri: Uri,
bytes: ByteArray,
mode: String
): Exception? =
try {
context.contentResolver.openOutputStream(uri, mode)?.use { it.write(bytes) }
null
} catch (e: Exception) {
e
}
fun append(context: Context, uri: Uri, bytes: ByteArray): Exception? =
writeBytes(context, uri, bytes, "wa")
fun write(context: Context, uri: Uri, bytes: ByteArray): Exception? =
writeBytes(context, uri, bytes, "w")
fun truncateAndWrite(context: Context, uri: Uri, bytes: ByteArray): Exception? =
writeBytes(context, uri, bytes, "wt")
fun createAndWrite(
context: Context,
location: Location,
filename: String,
mimeType: String,
bytes: ByteArray
): Pair<Uri, Exception?> =
create(location, context, filename, mimeType).let { (uri, e) ->
if (e is Exception) Pair(Uri.EMPTY, e)
else {
val we = writeBytes(context, uri, bytes, "w")
if (we is Exception) {
deleteFile(uri)
Pair(Uri.EMPTY, we)
}
else
Pair(uri, null)
}
}
fun deleteFile(uri: Uri): Boolean {
return try {
if (uri == Uri.EMPTY) false
else uri.toFile().delete()
}
catch (e: Exception) { false }
}
fun renameTo(fromUri: Uri, toUri: Uri) {
fromUri.toFile().renameTo(toUri.toFile())
}
}