changes to save scheduled message attachment data in app local dir so external delete of attachment file doesn't result in it being unable to be found when sending message

This commit is contained in:
gavine99
2025-02-20 20:41:49 +11:00
parent 1eebb9cc8e
commit 2706a558b7
17 changed files with 551 additions and 309 deletions
@@ -0,0 +1,156 @@
/*
* 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.extensions
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.core.net.toFile
fun Uri.isEmpty() = this == Uri.EMPTY
fun Uri.isVCard(context: Context): Boolean = getType(context) == "text/x-vcard"
fun Uri.isAudio(context: Context): Boolean = getType(context).startsWith("audio/")
fun Uri.isImage(context: Context): Boolean = getType(context).startsWith("image/")
fun Uri.isVideo(context: Context): Boolean = getType(context).startsWith("video/")
fun Uri.isContact(context: Context): Boolean =
(getType(context).lowercase() == ContactsContract.Contacts.CONTENT_ITEM_TYPE)
fun Uri.getResourceBytes(context: Context): ByteArray =
try {
context.contentResolver.openInputStream(this)?.use {
it.readBytes()
} ?: ByteArray(0)
} catch (e: Exception) { ByteArray(0) }
fun Uri.resourceExists(context: Context): Boolean {
var retVal: Boolean? = null
try {
when (scheme) {
ContentResolver.SCHEME_CONTENT -> {
retVal = context.contentResolver.query(
this, null, null, null, null
)?.use { it.moveToFirst() }
}
ContentResolver.SCHEME_FILE -> retVal = this.toFile().exists()
}
} catch (e: Exception) { /* nothing */
}
return retVal ?: false
}
fun Uri.getType(context: Context): String {
var retVal: String? = null
when (scheme) {
ContentResolver.SCHEME_CONTENT -> retVal = context.contentResolver.getType(this)
ContentResolver.SCHEME_FILE -> retVal =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(this.toFile().extension)
}
return retVal ?: "application/octect-stream"
}
@SuppressLint("Range")
fun Uri.getName(context: Context): String? {
var retVal: String? = null
try {
when (scheme) {
ContentResolver.SCHEME_CONTENT -> {
context.contentResolver.query(
this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null
)?.use {
it.moveToFirst()
retVal = it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
}
}
ContentResolver.SCHEME_FILE -> retVal = this.toFile().name
}
} catch (e: Exception) { /* nothing */ }
return retVal
}
@SuppressLint("Range")
fun Uri.getSize(context: Context): Long {
var retVal: Long? = null
try {
when (scheme) {
ContentResolver.SCHEME_CONTENT -> {
context.contentResolver.query(
this, arrayOf(OpenableColumns.SIZE), null, null, null
)?.use {
it.moveToFirst()
retVal = it.getLong(it.getColumnIndex(OpenableColumns.SIZE))
}
}
ContentResolver.SCHEME_FILE -> retVal = this.toFile().length()
}
} catch (e: Exception) { /* nothing */
}
return retVal ?: -1
}
@SuppressLint("Range")
fun Uri.contactToVCard(context: Context): Uri =
try {
Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_VCARD_URI,
context.contentResolver.query(
this, null, null, null, null
)?.use {
it.moveToFirst()
it.getString(it.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)) ?: ""
}
)
} catch (e: Exception) {
Uri.EMPTY
}
fun Uri.getDefaultActivityIconForMimeType(context: Context): Drawable? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager
.queryIntentActivities(
Intent(Intent.ACTION_VIEW).setDataAndType(this, getType(context)),
PackageManager.ResolveInfoFlags.of(
PackageManager.MATCH_DEFAULT_ONLY.toLong()
)
).let {
if (it.size > 0) it[0].loadIcon(context.packageManager)
else null
}
} else {
context.packageManager
.resolveActivity(
Intent(Intent.ACTION_VIEW).setDataAndType(this, getType(context)),
PackageManager.MATCH_DEFAULT_ONLY)
?.loadIcon(context.packageManager)
}
@@ -18,13 +18,23 @@
*/
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.repository.ScheduledMessageRepository
import io.reactivex.Flowable
import io.realm.RealmList
import java.io.File
import java.util.UUID
import javax.inject.Inject
class AddScheduledMessage @Inject constructor(
private val scheduledMessageRepo: ScheduledMessageRepository,
private val updateScheduledMessageAlarms: UpdateScheduledMessageAlarms
private val updateScheduledMessageAlarms: UpdateScheduledMessageAlarms,
private val context: Context,
) : Interactor<AddScheduledMessage.Params>() {
data class Params(
@@ -36,13 +46,53 @@ class AddScheduledMessage @Inject constructor(
val attachments: List<String>
)
@SuppressLint("Range")
override fun buildObservable(params: Params): Flowable<*> {
// have to 3-step save scheduled message
return Flowable.just(params)
.map {
scheduledMessageRepo.saveScheduledMessage(it.date, it.subId, it.recipients, it.sendAsGroup, it.body,
it.attachments)
}
.flatMap { updateScheduledMessageAlarms.buildObservable(Unit) }
.map { // step 1 - save, as-is, to db to get primary key id
scheduledMessageRepo.saveScheduledMessage(
it.date, it.subId, it.recipients, it.sendAsGroup, it.body, it.attachments
)
}
.map { scheduledMessageDb ->
// step 2 - copy attachments to app local storage
scheduledMessageDb.attachments = RealmList(
*scheduledMessageDb.attachments.mapNotNull {
val inUri = Uri.parse(it)
try {
// get filename of input uri or use random uuid on fail to get
val filename = inUri.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}"
)
// 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) }
}
localUri.toString()
} catch (e: Exception) {
it // on any error, use original uri string
}
}.toTypedArray()
)
// step 3 - update scheduled message with new attachment uris
scheduledMessageRepo.updateScheduledMessage(scheduledMessageDb)
}
.flatMap { updateScheduledMessageAlarms.buildObservable(Unit) }
}
}
@@ -0,0 +1,51 @@
/*
* 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.interactor
import android.annotation.SuppressLint
import android.content.Context
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import io.reactivex.Flowable
import java.io.File
import javax.inject.Inject
class DeleteScheduledMessages @Inject constructor(
private val scheduledMessageRepo: ScheduledMessageRepository,
private val context: Context,
) : Interactor<List<Long>>() {
@SuppressLint("Range")
override fun buildObservable(scheduledMessageIds: List<Long>): Flowable<*> {
return Flowable.just(scheduledMessageIds)
.map {
try {
// for each message id to delete
it.forEach {
// recursively delete scheduled message top level dir
val topDir = File(context.filesDir, "scheduled-${it}")
// topDir.exists() && topDir.deleteRecursively()
}
} catch (e: Exception) { /* nothing */ }
// delete the db entries
scheduledMessageRepo.deleteScheduledMessages(it)
}
}
}
@@ -32,26 +32,27 @@ import javax.inject.Inject
class SendScheduledMessage @Inject constructor(
private val context: Context,
private val scheduledMessageRepo: ScheduledMessageRepository,
private val deleteScheduledMessagesInteractor: DeleteScheduledMessages,
private val sendMessage: SendMessage
) : Interactor<Long>() {
override fun buildObservable(params: Long): Flowable<*> {
return Flowable.just(params)
.mapNotNull(scheduledMessageRepo::getScheduledMessage)
.flatMap { message ->
if (message.sendAsGroup) {
listOf(message)
} else {
message.recipients.map { recipient -> message.copy(recipients = RealmList(recipient)) }
}.toFlowable()
}
.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)
}
.flatMap(sendMessage::buildObservable)
.doOnNext { scheduledMessageRepo.deleteScheduledMessage(params) }
.mapNotNull(scheduledMessageRepo::getScheduledMessage)
.flatMap { message ->
if (message.sendAsGroup) {
listOf(message)
} else {
message.recipients.map { recipient -> message.copy(recipients = RealmList(recipient)) }
}.toFlowable()
}
.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)
}
.flatMap(sendMessage::buildObservable)
.doOnNext { deleteScheduledMessagesInteractor.execute(listOf(params)) }
}
}
@@ -23,11 +23,17 @@ import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.core.net.toFile
import androidx.core.view.inputmethod.InputContentInfoCompat
import dev.octoshrimpy.quik.extensions.contactToVCard
import dev.octoshrimpy.quik.extensions.getName
import dev.octoshrimpy.quik.extensions.getResourceBytes
import dev.octoshrimpy.quik.extensions.getSize
import dev.octoshrimpy.quik.extensions.getType
import dev.octoshrimpy.quik.extensions.isAudio
import dev.octoshrimpy.quik.extensions.isContact
import dev.octoshrimpy.quik.extensions.isImage
import dev.octoshrimpy.quik.extensions.isVCard
@SuppressLint("Range")
@@ -43,106 +49,35 @@ class Attachment (
uri = inputContent?.contentUri ?: uri
// if constructed with a uri to a contact, convert uri to associated vcard uri
if (context.contentResolver.getType(uri)?.lowercase() ==
ContactsContract.Contacts.CONTENT_ITEM_TYPE
) {
uri = try {
Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_VCARD_URI,
context.contentResolver.query(
uri, null, null, null, null
)?.use {
it.moveToFirst()
it.getString(it.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)) ?: ""
}
)
} catch (e: Exception) {
Uri.EMPTY
}
}
if (uri.isContact(context))
uri = uri.contactToVCard(context)
}
fun getType(context: Context): String {
var retVal: String? = null
when (uri.scheme) {
ContentResolver.SCHEME_CONTENT -> retVal = context.contentResolver.getType(uri)
ContentResolver.SCHEME_FILE -> retVal =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(uri.toFile().extension)
}
return retVal ?: "application/octect-stream"
}
fun isVCard(context: Context): Boolean = uri.isVCard(context)
fun getName(context: Context): String {
var retVal: String? = null
try {
when (uri.scheme) {
ContentResolver.SCHEME_CONTENT -> {
context.contentResolver.query(
uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null
)?.use {
it.moveToFirst()
retVal = it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
}
}
fun isAudio(context: Context): Boolean = uri.isAudio(context)
ContentResolver.SCHEME_FILE -> retVal = uri.toFile().name
}
} catch (e: Exception) { /* nothing */
}
fun isImage(context: Context): Boolean = uri.isImage(context)
return retVal ?: "unknown"
}
fun getType(context: Context): String = uri.getType(context)
fun isVCard(context: Context): Boolean {
return (getType(context) == "text/x-vcard")
}
fun getName(context: Context): String = uri.getName(context) ?: "unknown"
fun getSize(context: Context): Long = uri.getSize(context)
fun hasDisplayableImage(context: Context): Boolean {
val mimeType = getType(context)
return (mimeType.startsWith("image/") || mimeType.startsWith("video/"))
}
fun isAudio(context: Context): Boolean {
return (getType(context).startsWith("audio/"))
}
fun isImage(context: Context): Boolean {
return (getType(context).startsWith("image/"))
}
fun getSize(context: Context): Long {
var retVal: Long? = null
try {
when (uri.scheme) {
ContentResolver.SCHEME_CONTENT -> {
context.contentResolver.query(
uri, arrayOf(OpenableColumns.SIZE), null, null, null
)?.use {
it.moveToFirst()
retVal = it.getLong(it.getColumnIndex(OpenableColumns.SIZE))
}
}
ContentResolver.SCHEME_FILE -> retVal = uri.toFile().length()
}
} catch (e: Exception) { /* nothing */
}
return retVal ?: -1
}
fun getResourceBytes(context: Context): ByteArray {
// cache resource bytes by loading first time only
if (resourceBytes != null)
return resourceBytes!!
try {
context.contentResolver.openInputStream(uri)?.use {
resourceBytes = it.readBytes()
}
} catch (e: Exception) {
}
resourceBytes = uri.getResourceBytes(context)
return resourceBytes ?: ByteArray(0)
return resourceBytes!!
}
fun releaseResourceBytes() {
@@ -33,7 +33,9 @@ interface ScheduledMessageRepository {
sendAsGroup: Boolean,
body: String,
attachments: List<String>
)
): ScheduledMessage
fun updateScheduledMessage(scheduledMessage: ScheduledMessage)
/**
* Returns all of the scheduled messages, sorted chronologically
@@ -53,4 +55,7 @@ interface ScheduledMessageRepository {
// delete multiple scheduled messages by id list
fun deleteScheduledMessages(ids: List<Long>)
// get a list of all scheduled message ids (in scheduled date order)
fun getAllScheduledMessageIdsSnapshot(): List<Long>
}