Merge pull request #594 from Inhishonor/upgrade-smsmms-group-individual-send-no-wait-appear-delayed-mms-mms-receive-to-worker-send-ack-mmsc

Upgrade smsmms group individual send no wait appear delayed mms mms receive to worker send ack mmsc
This commit is contained in:
octoshrimpy
2025-12-09 21:51:39 -05:00
committed by GitHub
359 changed files with 20432 additions and 3917 deletions
@@ -26,6 +26,6 @@ data class SubscriptionInfoCompat(private val subscriptionInfo: SubscriptionInfo
val simSlotIndex get() = subscriptionInfo.simSlotIndex
val displayName get() = subscriptionInfo.displayName
val displayName: CharSequence get() = subscriptionInfo.displayName
}
@@ -58,7 +58,7 @@ class SubscriptionManagerCompat @Inject constructor(context: Context, private va
abstract class OnSubscriptionsChangedListener {
val listener: SubscriptionManager.OnSubscriptionsChangedListener? =
val listener: SubscriptionManager.OnSubscriptionsChangedListener =
object : SubscriptionManager.OnSubscriptionsChangedListener() {
override fun onSubscriptionsChanged() {
this@OnSubscriptionsChangedListener.onSubscriptionsChanged()
@@ -44,7 +44,7 @@ class ContactAddedListenerImpl @Inject constructor(
private class ContactContentObserver(context: Context) : ContentObserver(Handler()) {
private val subject = BehaviorSubject.createDefault<Unit>(Unit)
private val subject = BehaviorSubject.createDefault(Unit)
val observable: Observable<Unit> = subject
.doOnSubscribe { context.contentResolver.registerContentObserver(URI, true, this) }
@@ -50,12 +50,6 @@ class BluetoothMicManager(
})
}
enum class StartBluetoothDevice {
NoDevice,
Connecting,
Connected
}
var device: AudioDeviceInfo? = null
private set
@@ -36,7 +36,7 @@ class ChangelogManagerImpl @Inject constructor(
private val prefs: Preferences
) : ChangelogManager {
override fun didUpdate(): Boolean = (prefs.changelogVersion.get() ?: 0) != context.versionCode
override fun didUpdate(): Boolean = prefs.changelogVersion.get() != context.versionCode
override suspend fun getChangelog(): ChangelogManager.CumulativeChangelog {
val listType = Types.newParameterizedType(List::class.java, Changeset::class.java)
@@ -49,7 +49,7 @@ class ChangelogManagerImpl @Inject constructor(
.orEmpty()
.sortedBy { changelog -> changelog.versionCode }
.filter { changelog ->
changelog.versionCode in (prefs.changelogVersion.get() ?: 0).inc()..context.versionCode
changelog.versionCode in prefs.changelogVersion.get().inc()..context.versionCode
}
ChangelogManager.CumulativeChangelog(
@@ -40,8 +40,7 @@ object MediaRecorderManager : MediaRecorder() {
const val AUDIO_FILE_PREFIX = "recorded-"
const val AUDIO_FILE_SUFFIX = ".3ga"
var recordingState: RecordingState = RecordingState.Initial
private set
private var recordingState: RecordingState = RecordingState.Initial
var uri: Uri = Uri.EMPTY
private set
@@ -64,7 +63,7 @@ object MediaRecorderManager : MediaRecorder() {
fun startRecording(context: Context, preferredAudioDevice: AudioDeviceInfo? = null): Uri {
return try {
val (newUri, e) = FileUtils.create(
FileUtils.Companion.Location.Cache,
FileUtils.Location.Cache,
context,
"$AUDIO_FILE_PREFIX${UUID.randomUUID()}$AUDIO_FILE_SUFFIX",
""
@@ -0,0 +1,631 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2025
*
* modified from original for QUIK
*
* 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 com.moez.QKSMS.manager
import android.app.PendingIntent
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Telephony
import android.telephony.SmsManager
import android.telephony.SmsMessage
import androidx.core.content.contentValuesOf
import androidx.core.net.toUri
import com.android.mms.MmsConfig
import com.android.mms.dom.smil.parser.SmilXmlSerializer
import com.android.mms.util.DownloadManager
import com.android.mms.util.RateController
import com.google.android.mms.ContentType
import com.google.android.mms.InvalidHeaderValueException
import com.google.android.mms.MMSPart
import com.google.android.mms.MmsException
import com.google.android.mms.pdu_alt.CharacterSets
import com.google.android.mms.pdu_alt.EncodedStringValue
import com.google.android.mms.pdu_alt.GenericPdu
import com.google.android.mms.pdu_alt.PduBody
import com.google.android.mms.pdu_alt.PduComposer
import com.google.android.mms.pdu_alt.PduHeaders
import com.google.android.mms.pdu_alt.PduPart
import com.google.android.mms.pdu_alt.PduPersister
import com.google.android.mms.pdu_alt.SendReq
import com.google.android.mms.smil.SmilHelper
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.MmsSentReceiver
import com.klinker.android.send_message.SmsManagerFactory
import com.klinker.android.send_message.StripAccents
import com.klinker.android.send_message.Utils
import timber.log.Timber
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Calendar
import java.util.UUID
object QkTransaction {
private const val DEFAULT_EXPIRY_TIME: Long = (7 * 24 * 60 * 60).toLong()
private const val DEFAULT_PRIORITY: Int = PduHeaders.PRIORITY_NORMAL
private fun getNumSmsPages(stripUnicode: Boolean, body: String?): Int {
var text = body
if (stripUnicode) {
text = StripAccents.stripAccents(text)
}
val data = SmsMessage.calculateLength(text, false)
return data[0]
}
private fun checkMMS(
body: String?, numToAddresses: Int, numParts: Int, asGroup: Boolean, longAsMms: Boolean,
stripUnicode: Boolean
): Boolean {
return (numParts > 0) ||
((numToAddresses > 1) && asGroup) ||
(longAsMms && getNumSmsPages(stripUnicode, body) > 3)
}
fun createMessage(
context: Context,
subscriptionId: Int,
body: String?,
signature: String,
toAddresses: Array<String>,
parts: MutableCollection<MMSPart>,
asGroup: Boolean,
longAsMms: Boolean,
stripUnicode: Boolean
): Uri {
Timber.v("creating message")
// add signature to original text to be saved in db
var text = body
if (signature.isNotEmpty())
text += "\n$signature"
// strip unicode if flagged to do so
if (stripUnicode)
text = StripAccents.stripAccents(text)
if (checkMMS(text, toAddresses.size, parts.size, asGroup, longAsMms, stripUnicode)) {
RateController.init(context)
DownloadManager.init(context)
return createMmsMessage(context, subscriptionId, text, toAddresses, parts)
}
return createSmsMessage(context, subscriptionId, text, toAddresses)
}
fun explodeMessage(context: Context, messageUri: Uri, asGroup: Boolean): Collection<Uri> {
Timber.v("exploding message uri $messageUri")
if (asGroup)
return listOf(messageUri)
return if (messageUri.toString().startsWith(Telephony.Mms.CONTENT_URI.toString()))
explodeMmsMessage(context, messageUri)
else explodeSmsMessage(context, messageUri)
}
fun sendMessage(context: Context, messageUri: Uri, sentIntent: Intent, deliveryIntent: Intent?
): Boolean {
Timber.v("sending message uri $messageUri")
return if (messageUri.toString().startsWith(Telephony.Mms.CONTENT_URI.toString()))
sendMmsMessage(context, messageUri, sentIntent)
else sendSmsMessage(context, messageUri, sentIntent, deliveryIntent)
}
private fun getProviderRecipients(context: Context, threadId: Long): Collection<String> {
// get recipient ids
val spaceSeparatedRecipients = context.contentResolver.query(
(Telephony.MmsSms.CONTENT_CONVERSATIONS_URI.toString() + "?simple=true").toUri(),
arrayOf(Telephony.Threads._ID, Telephony.Threads.RECIPIENT_IDS),
Telephony.Threads._ID + " = ?", arrayOf(threadId.toString()),
null
)
?.use { cursor ->
if (cursor.moveToFirst())
cursor.getString(1)
else {
Timber.e("recipient id provider db query returned no rows")
""
}
}
?: let {
Timber.e("recipient id provider db query failed")
""
}
if (spaceSeparatedRecipients.isEmpty()) {
Timber.e("failed to get provider recipient ids for thread $threadId")
return listOf()
}
// get addresses from recipient ids
val addresses = ArrayList<String>()
context.contentResolver.query(
"content://mms-sms/canonical-addresses".toUri(),
arrayOf(
Telephony.CanonicalAddressesColumns._ID,
Telephony.CanonicalAddressesColumns.ADDRESS
),
Telephony.CanonicalAddressesColumns._ID + " in (" +
spaceSeparatedRecipients.replace(' ', ',') + ")",
null,
null
)
?.use { cursor ->
if (cursor.moveToFirst())
do {
addresses.add(cursor.getString(1))
} while (cursor.moveToNext())
else
Timber.e("address provider db query returned no rows")
}
?: let { Timber.e("address provider db query failed") }
if (addresses.isEmpty())
Timber.e("no addresses from recipient ids for thread $threadId")
return addresses
}
private fun createSmsMessage(
context: Context, subscriptionId: Int, body: String?, addresses: Array<String>
): Uri {
val threadId = Utils.getOrCreateThreadId(context, addresses.toSet())
val cal = Calendar.getInstance()
val values = ContentValues()
values.put(Telephony.Sms.ADDRESS, if (addresses.size > 1) "" else addresses[0])
values.put(Telephony.Sms.BODY, body)
values.put(Telephony.Sms.DATE, cal.timeInMillis.toString() + "")
values.put(Telephony.Sms.READ, 1)
values.put(Telephony.Sms.TYPE, 4)
values.put(Telephony.Sms.THREAD_ID, threadId)
values.put(Telephony.Sms.SUBSCRIPTION_ID, subscriptionId)
val messageUri = context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values)
if (messageUri == null) {
Timber.e("unable to create sms provider record")
return Uri.EMPTY
}
return messageUri
}
private fun explodeSmsMessage(context: Context, messageUri: Uri): Collection<Uri> {
val retVal: MutableCollection<Uri> = ArrayList()
var threadId: Long = -1
var subscriptionId = -1
var body = ""
// get pertinent message values of source message
context.contentResolver.query(
messageUri,
arrayOf(Telephony.Sms.THREAD_ID, Telephony.Sms.SUBSCRIPTION_ID, Telephony.Sms.BODY),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
threadId = cursor.getInt(0).toLong()
subscriptionId = cursor.getInt(1)
body = cursor.getString(2)
} else {
Timber.e("provider db query returned no rows")
return retVal
}
}
?: let {
Timber.e("provider db query failed")
return retVal
}
// get thread recipients
val addresses = getProviderRecipients(context, threadId)
// if zero (!) or one recipient in thread, return original message only
if (addresses.size <= 1) {
retVal.add(messageUri)
return retVal
}
// create individual messages
for (address in addresses)
retVal.add(createSmsMessage(context, subscriptionId, body, arrayOf(address)))
return retVal
}
private fun sendSmsMessage(
context: Context, messageUri: Uri, sentIntent: Intent, deliveryIntent: Intent?
): Boolean {
if (messageUri === Uri.EMPTY) {
Timber.e("can't send sms. message uri is empty")
return false
}
var id = -1
var subscriptionId = -1
var body = ""
var address = ""
// get message values from provider db
context.contentResolver.query(
messageUri,
arrayOf(
Telephony.Sms._ID,
Telephony.Sms.SUBSCRIPTION_ID,
Telephony.Sms.ADDRESS,
Telephony.Sms.BODY
),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
id = cursor.getInt(0)
subscriptionId = cursor.getInt(1)
address = cursor.getString(2)
body = cursor.getString(3)
} else {
Timber.e("sms provider db query returned no rows")
return false
}
}
?: let {
Timber.e("sms provider db query failed")
return false
}
val sPI = ArrayList<PendingIntent>()
val dPI = ArrayList<PendingIntent>()
// set up sent and delivered pending intents to be used with message request
val sentPI = PendingIntent.getBroadcast(
context, id, sentIntent.setData(messageUri),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val deliveredPI =
if (deliveryIntent != null) PendingIntent.getBroadcast(
context, -id, deliveryIntent.setData(messageUri),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
else null
val smsManager = SmsManagerFactory.createSmsManager(subscriptionId)
val parts = smsManager.divideMessage(body)
// add pending intent for each part
for (i in parts.indices) {
sPI.add(sentPI)
if (deliveredPI != null) dPI.add(deliveredPI)
}
Timber.v("send sms message uri $messageUri")
try {
smsManager.sendMultipartTextMessage(
address, null, parts, sPI, dPI.ifEmpty { null }
)
} catch (e: Exception) {
Timber.e("send sms exception", e)
}
return true
}
private fun createMmsMessage(
context: Context, subscriptionId: Int, text: String?, addresses: Array<String>,
parts: MutableCollection<MMSPart>
): Uri {
// add text to the end of the part and send
if (!text.isNullOrEmpty())
parts.add(MMSPart().apply {
Name = "text"
MimeType = "text/plain"
Data = text.toByteArray()
})
try {
return PduPersister.getPduPersister(context).persist(
buildPdu(context, subscriptionId, addresses, ArrayList(parts)),
Telephony.Mms.Outbox.CONTENT_URI, true, true,
null, subscriptionId
)
} catch (e: Exception) {
Timber.e("failed to create mms message", e)
}
return Uri.EMPTY
}
private fun explodeMmsMessage(context: Context, messageUri: Uri): Collection<Uri> {
val retVal: MutableCollection<Uri> = ArrayList()
Timber.v("explode mms message $messageUri")
// load message from provider db as a generic pdu
val pdu: GenericPdu
try {
pdu = PduPersister.getPduPersister(context).load(messageUri)
} catch (e: MmsException) {
Timber.e("load pdu from provider failed", e)
return retVal
}
// get recipient addresses from pdu
val sendReq = pdu as SendReq
val encodedTos = sendReq.to
// if one recipient in thread, return original message only
if (encodedTos.size == 1) {
Timber.v("single recipient thread")
retVal.add(messageUri)
return retVal
}
// get subscription id from provider
val subscriptionId = context.contentResolver.query(
messageUri,
arrayOf(Telephony.Mms.SUBSCRIPTION_ID),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
cursor.getInt(0)
} else {
Timber.e("sub id provider db query returned no rows")
return retVal
}
}
?: let {
Timber.e("sub id provider db query failed")
return retVal
}
// create individual messages
for (encodedTo in encodedTos) {
try {
sendReq.to = arrayOf(encodedTo)
retVal.add(
PduPersister.getPduPersister(context).persist(
sendReq,
Telephony.Mms.Outbox.CONTENT_URI,
true,
true,
null,
subscriptionId
)
)
} catch (e: Exception) {
Timber.e("failed creating provider mms message", e)
}
}
return retVal
}
private fun sendMmsMessage(context: Context, messageUri: Uri, sentIntent: Intent): Boolean {
try {
Timber.v("send mms message uri $messageUri")
// update message status to outbox in provider
if (SqliteWrapper.update(
context, context.contentResolver,
messageUri,
contentValuesOf(
Telephony.Mms.MESSAGE_BOX to Telephony.Mms.MESSAGE_BOX_OUTBOX
),
null, null
) <= 0)
Timber.v("failed to update $messageUri to mms outbox")
// get mms id and subscription id from provider
var id = -1
var subscriptionId = -1
context.contentResolver.query(
messageUri,
arrayOf(Telephony.Mms._ID, Telephony.Mms.SUBSCRIPTION_ID),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
id = cursor.getInt(0)
subscriptionId = cursor.getInt(1)
} else {
Timber.e("sub id provider db query returned no rows")
Utils.getDefaultSubscriptionId()
}
}
?: let {
Timber.e("sub id provider db query failed")
Utils.getDefaultSubscriptionId()
}
// load message from provider db as a generic pdu
val sendPdu = try {
PduPersister.getPduPersister(context).load(messageUri)
} catch (e: MmsException) {
Timber.e("pdu from provider db failed", e)
return false
}
val fileName = "send." + UUID.randomUUID() + ".dat"
val mSendFile = File(context.cacheDir, fileName)
Timber.v("using file name $fileName")
val contentUri = try {
FileOutputStream(mSendFile).use {
it.write(PduComposer(context, sendPdu).make())
}
(Uri.Builder())
.authority(context.packageName + ".MmsFileProvider")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build()
} catch (e: IOException) {
Timber.e("error writing send file", e)
return false
}
// build intent to send when message sent
val pendingIntent = PendingIntent.getBroadcast(
context,
id,
sentIntent
.setData(messageUri)
.putExtra(MmsSentReceiver.EXTRA_FILE_PATH, mSendFile.path),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
SmsManagerFactory.createSmsManager(subscriptionId).sendMultimediaMessage(
context,
contentUri,
null,
Bundle().apply { putBoolean(SmsManager.MMS_CONFIG_GROUP_MMS_ENABLED, true) },
pendingIntent
)
} catch (e: Exception) {
Timber.e("failed sending mms", e)
return false
}
return true
}
private fun buildPdu(
context: Context, subscriptionId: Int, recipients: Array<String>, parts: List<MMSPart>
): SendReq {
val req = SendReq()
// From, per spec
req.prepareFromAddress(context, "", subscriptionId)
// To
for (recipient in recipients)
req.addTo(EncodedStringValue(recipient))
// Subject { commented but left for future use }
// if (subject.isNotEmpty())
// req.subject = EncodedStringValue(subject)
// Date
req.date = System.currentTimeMillis() / 1000
// Body
val body = PduBody()
var size = 0
// Add text part. Always add a smil part for compatibility, without it there
// may be issues on some carriers/client apps
parts.forEach { size += addTextPart(body, it) }
// add a SMIL document for compatibility
val out = ByteArrayOutputStream()
SmilXmlSerializer.serialize(SmilHelper.createSmilDocument(body), out)
body.addPart(0, PduPart().apply {
contentId = "smil".toByteArray()
contentLocation = "smil.xml".toByteArray()
contentType = ContentType.APP_SMIL.toByteArray()
data = out.toByteArray()
})
req.body = body
// Message size
req.messageSize = size.toLong()
// Message class
req.messageClass = PduHeaders.MESSAGE_CLASS_PERSONAL_STR.toByteArray()
// Expiry
req.expiry = DEFAULT_EXPIRY_TIME
try {
// Priority
req.priority = DEFAULT_PRIORITY
// Delivery report
req.deliveryReport = PduHeaders.VALUE_NO
// Read report
req.readReport = PduHeaders.VALUE_NO
} catch (e: InvalidHeaderValueException) {
Timber.e("invalid header value when building pdu")
}
return req
}
private fun addTextPart(pb: PduBody, p: MMSPart): Int {
val filename = p.Name
val part = PduPart().apply {
// Set Charset if it's a text media.
if (p.MimeType.startsWith("text"))
charset = CharacterSets.UTF_8
// Set Content-Type.
contentType = p.MimeType.toByteArray()
// Set Content-Location.
contentLocation = filename.toByteArray()
val index = filename.lastIndexOf(".")
contentId =
(
if (index == -1) filename
else filename.substring(0, index)
).toByteArray()
data = p.Data
}
pb.addPart(part)
return part.data.size
}
}
@@ -24,22 +24,20 @@ import android.content.Context
import android.content.Intent
import com.klinker.android.send_message.BroadcastUtils
import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.nonDebugPackageName
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
class WidgetManagerImpl @Inject constructor(
private val context: Context,
private val prefs: Preferences
) : WidgetManager {
class WidgetManagerImpl @Inject constructor(private val context: Context, prefs: Preferences)
: WidgetManager {
companion object {
private var staticUnreadAtTopPrefsDisposable = AtomicReference<Disposable>(null)
fun sendDatasetChanged(context: Context) {
BroadcastUtils.sendExplicitBroadcast(context, Intent(), WidgetManager.ACTION_NOTIFY_DATASET_CHANGED)
BroadcastUtils.sendExplicitBroadcast(context, Intent(), "${context.packageName}.${WidgetManager.ACTION_NOTIFY_DATASET_CHANGED}")
}
}
@@ -61,7 +59,12 @@ class WidgetManagerImpl @Inject constructor(
override fun updateTheme() {
val ids = AppWidgetManager.getInstance(context)
.getAppWidgetIds(ComponentName(context.packageName, "dev.octoshrimpy.quik.feature.widget.WidgetProvider"))
.getAppWidgetIds(
ComponentName(
context.packageName,
"${nonDebugPackageName(context.packageName)}.feature.widget.WidgetProvider"
)
)
val intent = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
@@ -32,7 +32,7 @@ class CursorToContactImpl @Inject constructor(
) : CursorToContact {
companion object {
val URI = Phone.CONTENT_URI
val URI = Phone.CONTENT_URI!!
val PROJECTION = arrayOf(
Phone._ID,
Phone.LOOKUP_KEY,
@@ -20,7 +20,6 @@ package dev.octoshrimpy.quik.mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony.Mms
import android.provider.Telephony.MmsSms
import android.provider.Telephony.Sms
@@ -34,16 +33,16 @@ import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.SqliteWrapper
import dev.octoshrimpy.quik.util.tryOrNull
import javax.inject.Inject
import androidx.core.net.toUri
class CursorToMessageImpl @Inject constructor(
private val context: Context,
private val cursorToPart: CursorToPart,
private val keys: KeyManager,
private val permissionManager: PermissionManager,
private val preferences: Preferences
) : CursorToMessage {
private val uri = Uri.parse("content://mms-sms/complete-conversations")
private val uri = "content://mms-sms/complete-conversations".toUri()
private val projection = arrayOf(
MmsSms.TYPE_DISCRIMINATOR_COLUMN,
MmsSms._ID,
@@ -67,7 +66,7 @@ class CursorToMessageImpl @Inject constructor(
Mms.MESSAGE_BOX,
Mms.DELIVERY_REPORT,
Mms.READ_REPORT,
MmsSms.PendingMessages.ERROR_TYPE,
// MmsSms.PendingMessages.ERROR_TYPE,
Mms.STATUS
)
@@ -78,8 +77,8 @@ class CursorToMessageImpl @Inject constructor(
return Message().apply {
type = when {
cursor.getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN) != -1 -> cursor.getString(columnsMap.msgType)
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> "mms"
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> "sms"
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> Message.TYPE_MMS
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> Message.TYPE_SMS
else -> "unknown"
}
@@ -93,7 +92,8 @@ class CursorToMessageImpl @Inject constructor(
subId = if (columnsMap.subId != -1) cursor.getInt(columnsMap.subId) else -1
when (type) {
"sms" -> {
Message.TYPE_SMS -> {
type = Message.TYPE_SMS
address = cursor.getString(columnsMap.smsAddress) ?: ""
boxId = cursor.getInt(columnsMap.smsType)
seen = cursor.getInt(columnsMap.smsSeen) != 0
@@ -106,14 +106,15 @@ class CursorToMessageImpl @Inject constructor(
deliveryStatus = cursor.getInt(columnsMap.smsStatus)
}
"mms" -> {
Message.TYPE_MMS -> {
type = Message.TYPE_MMS
address = getMmsAddress(contentId)
boxId = cursor.getInt(columnsMap.mmsMessageBox)
date *= 1000L
dateSent *= 1000L
seen = cursor.getInt(columnsMap.mmsSeen) != 0
mmsDeliveryStatusString = cursor.getString(columnsMap.mmsDeliveryReport) ?: ""
errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
// errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
messageSize = 0
readReportString = cursor.getString(columnsMap.mmsReadReport) ?: ""
messageType = cursor.getInt(columnsMap.mmsMessageType)
@@ -20,10 +20,10 @@ package dev.octoshrimpy.quik.mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import dev.octoshrimpy.quik.manager.PermissionManager
import dev.octoshrimpy.quik.model.Recipient
import javax.inject.Inject
import androidx.core.net.toUri
class CursorToRecipientImpl @Inject constructor(
private val context: Context,
@@ -31,7 +31,7 @@ class CursorToRecipientImpl @Inject constructor(
) : CursorToRecipient {
companion object {
val URI = Uri.parse("content://mms-sms/canonical-addresses")
val URI = "content://mms-sms/canonical-addresses".toUri()
const val COLUMN_ID = 0
const val COLUMN_ADDRESS = 1
@@ -28,6 +28,7 @@ import io.realm.FieldAttribute
import io.realm.RealmList
import io.realm.RealmMigration
import io.realm.Sort
import timber.log.Timber
import javax.inject.Inject
class QkRealmMigration @Inject constructor(
@@ -36,7 +37,7 @@ class QkRealmMigration @Inject constructor(
) : RealmMigration {
companion object {
const val SchemaVersion: Long = 14
const val SCHEMA_VERSION: Long = 14
}
@SuppressLint("ApplySharedPref")
@@ -45,82 +46,82 @@ class QkRealmMigration @Inject constructor(
if (version == 0L) {
realm.schema.get("MmsPart")
?.removeField("image")
?.removeField("image")
version++
}
if (version == 1L) {
realm.schema.get("Message")
?.addField("subId", Int::class.java)
?.addField("subId", Int::class.java)
version++
}
if (version == 2L) {
realm.schema.get("Conversation")
?.addField("name", String::class.java, FieldAttribute.REQUIRED)
?.addField("name", String::class.java, FieldAttribute.REQUIRED)
version++
}
if (version == 3L) {
realm.schema.create("ScheduledMessage")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("date", Long::class.java, FieldAttribute.REQUIRED)
.addField("subId", Long::class.java, FieldAttribute.REQUIRED)
.addRealmListField("recipients", String::class.java)
.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
.addField("body", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("attachments", String::class.java)
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("date", Long::class.java, FieldAttribute.REQUIRED)
.addField("subId", Long::class.java, FieldAttribute.REQUIRED)
.addRealmListField("recipients", String::class.java)
.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
.addField("body", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("attachments", String::class.java)
version++
}
if (version == 4L) {
realm.schema.get("Conversation")
?.addField("pinned", Boolean::class.java, FieldAttribute.REQUIRED, FieldAttribute.INDEXED)
?.addField("pinned", Boolean::class.java, FieldAttribute.REQUIRED, FieldAttribute.INDEXED)
version++
}
if (version == 5L) {
realm.schema.create("BlockedNumber")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("address", String::class.java, FieldAttribute.REQUIRED)
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("address", String::class.java, FieldAttribute.REQUIRED)
version++
}
if (version == 6L) {
realm.schema.get("Conversation")
?.addField("blockingClient", Integer::class.java)
?.addField("blockReason", String::class.java)
?.addField("blockingClient", Integer::class.java)
?.addField("blockReason", String::class.java)
realm.schema.get("MmsPart")
?.addField("seq", Integer::class.java, FieldAttribute.REQUIRED)
?.addField("name", String::class.java)
?.addField("seq", Integer::class.java, FieldAttribute.REQUIRED)
?.addField("name", String::class.java)
version++
}
if (version == 7L) {
realm.schema.get("Conversation")
?.addRealmObjectField("lastMessage", realm.schema.get("Message"))
?.removeField("count")
?.removeField("date")
?.removeField("snippet")
?.removeField("read")
?.removeField("me")
?.addRealmObjectField("lastMessage", realm.schema.get("Message"))
?.removeField("count")
?.removeField("date")
?.removeField("snippet")
?.removeField("read")
?.removeField("me")
val conversations = realm.where("Conversation")
.findAll()
.findAll()
val messages = realm.where("Message")
.sort("date", Sort.DESCENDING)
.distinct("threadId")
.findAll()
.associateBy { message -> message.getLong("threadId") }
.sort("date", Sort.DESCENDING)
.distinct("threadId")
.findAll()
.associateBy { message -> message.getLong("threadId") }
conversations.forEach { conversation ->
conversation.setObject("lastMessage", messages[conversation.getLong("id")])
@@ -134,44 +135,44 @@ class QkRealmMigration @Inject constructor(
realm.delete("PhoneNumber")
realm.schema.create("ContactGroup")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("title", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("contacts", realm.schema.get("Contact"))
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("title", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("contacts", realm.schema.get("Contact"))
realm.schema.get("PhoneNumber")
?.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
?.addField("accountType", String::class.java)
?.addField("isDefault", Boolean::class.java, FieldAttribute.REQUIRED)
?.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
?.addField("accountType", String::class.java)
?.addField("isDefault", Boolean::class.java, FieldAttribute.REQUIRED)
val phoneNumbers = cursorToContact.getContactsCursor()
?.map(cursorToContact::map)
?.distinctBy { contact -> contact.numbers.firstOrNull()?.id } // Each row has only one number
?.groupBy { contact -> contact.lookupKey }
?: mapOf()
?.map(cursorToContact::map)
?.distinctBy { contact -> contact.numbers.firstOrNull()?.id } // Each row has only one number
?.groupBy { contact -> contact.lookupKey }
?: mapOf()
realm.schema.get("Contact")
?.addField("starred", Boolean::class.java, FieldAttribute.REQUIRED)
?.addField("photoUri", String::class.java)
?.transform { realmContact ->
val numbers = RealmList<DynamicRealmObject>()
phoneNumbers[realmContact.get("lookupKey")]
?.flatMap { contact -> contact.numbers }
?.map { number ->
realm.createObject("PhoneNumber", number.id).apply {
setString("accountType", number.accountType)
setString("address", number.address)
setString("type", number.type)
}
}
?.let(numbers::addAll)
?.addField("starred", Boolean::class.java, FieldAttribute.REQUIRED)
?.addField("photoUri", String::class.java)
?.transform { realmContact ->
val numbers = RealmList<DynamicRealmObject>()
phoneNumbers[realmContact.get("lookupKey")]
?.flatMap { contact -> contact.numbers }
?.map { number ->
realm.createObject("PhoneNumber", number.id).apply {
setString("accountType", number.accountType)
setString("address", number.address)
setString("type", number.type)
}
}
?.let(numbers::addAll)
val photoUri = phoneNumbers[realmContact.get("lookupKey")]
?.firstOrNull { number -> number.photoUri != null }
?.photoUri
val photoUri = phoneNumbers[realmContact.get("lookupKey")]
?.firstOrNull { number -> number.photoUri != null }
?.photoUri
realmContact.setList("numbers", numbers)
realmContact.setString("photoUri", photoUri)
}
realmContact.setList("numbers", numbers)
realmContact.setString("photoUri", photoUri)
}
// Migrate conversation themes
val recipients = mutableMapOf<Long, Int>() // Map of recipientId:theme
@@ -225,11 +226,11 @@ class QkRealmMigration @Inject constructor(
if (version == 10L) {
realm.schema.get("MmsPart")
?.addField("messageId", Long::class.java, FieldAttribute.INDEXED, FieldAttribute.REQUIRED)
?.transform { part ->
val messageId = part.linkingObjects("Message", "parts").firstOrNull()?.getLong("contentId") ?: 0
part.setLong("messageId", messageId)
}
?.addField("messageId", Long::class.java, FieldAttribute.INDEXED, FieldAttribute.REQUIRED)
?.transform { part ->
val messageId = part.linkingObjects("Message", "parts").firstOrNull()?.getLong("contentId") ?: 0
part.setLong("messageId", messageId)
}
version++
}
@@ -246,6 +247,19 @@ class QkRealmMigration @Inject constructor(
.addField("isRegex", Boolean::class.java, FieldAttribute.REQUIRED)
.addField("includeContacts", Boolean::class.java, FieldAttribute.REQUIRED)
realm.schema.get("Conversation")
?.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
?.transform { conversation ->
conversation.setBoolean(
"sendAsGroup",
(conversation.getList("recipients").size > 1)
)
}
realm.schema.get("Message")
?.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
version++
}
@@ -280,7 +294,17 @@ class QkRealmMigration @Inject constructor(
version++
}
check(version >= newVersion) { "Migration missing from v$oldVersion to v$newVersion" }
check(version >= SCHEMA_VERSION) {
"Migration from v$oldVersion to v$newVersion failed at v$version"
}
// throw an exception if migration failed
check(version >= newVersion) {
"Realm migration from v$oldVersion to v$newVersion after v$version"
}
// else
Timber.d("Realm migration from v$oldVersion to v$newVersion succeeded")
}
}
@@ -42,6 +42,8 @@ class BlockThreadReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
val threadId = intent.getLongExtra("threadId", 0)
blockingClient
@@ -23,19 +23,25 @@ import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.DeleteMessages
import timber.log.Timber
import javax.inject.Inject
class DeleteMessagesReceiver : BroadcastReceiver() {
@Inject lateinit var deleteMessages: DeleteMessages
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
val messageIds = intent.getLongArrayExtra("messageIds") ?: longArrayOf()
deleteMessages.execute(DeleteMessages.Params(messageIds.toList(), threadId)) { pendingResult.finish() }
Timber.v("received")
intent.getLongExtra("threadId", 0).takeIf { it > 0 }?.let { threadId ->
intent.getLongArrayExtra("messageIds")?.let { messageIds ->
val pendingResult = goAsync()
deleteMessages.execute(DeleteMessages.Params(messageIds.toList(), threadId)) {
pendingResult.finish()
}
}
}
}
}
@@ -1,40 +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.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkArchived
import javax.inject.Inject
class MarkArchivedReceiver : BroadcastReceiver() {
@Inject lateinit var markArchived: MarkArchived
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
markArchived.execute(listOf(threadId)) { pendingResult.finish() }
}
}
@@ -1,40 +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.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkRead
import javax.inject.Inject
class MarkReadReceiver : BroadcastReceiver() {
@Inject lateinit var markRead: MarkRead
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
markRead.execute(listOf(threadId)) { pendingResult.finish() }
}
}
@@ -1,40 +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.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkSeen
import javax.inject.Inject
class MarkSeenReceiver : BroadcastReceiver() {
@Inject lateinit var markSeen: MarkSeen
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
markSeen.execute(threadId) { pendingResult.finish() }
}
}
@@ -25,9 +25,13 @@ import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkDelivered
import dev.octoshrimpy.quik.interactor.MarkDeliveryFailed
import timber.log.Timber
import javax.inject.Inject
class SmsDeliveredReceiver : BroadcastReceiver() {
class MessageDeliveredReceiver : BroadcastReceiver() {
companion object {
const val EXTRA_QUIK_MESSAGE_ID = "messageId"
}
@Inject lateinit var markDelivered: MarkDelivered
@Inject lateinit var markDeliveryFailed: MarkDeliveryFailed
@@ -35,21 +39,25 @@ class SmsDeliveredReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val id = intent.getLongExtra("id", 0L)
Timber.v("received")
when (resultCode) {
// TODO notify about delivery
Activity.RESULT_OK -> {
intent.extras?.getLong(EXTRA_QUIK_MESSAGE_ID)?.takeIf { it > 0 }
?.let { messageId ->
val pendingResult = goAsync()
markDelivered.execute(id) { pendingResult.finish() }
}
// TODO notify about delivery failure
Activity.RESULT_CANCELED -> {
val pendingResult = goAsync()
markDeliveryFailed.execute(MarkDeliveryFailed.Params(id, resultCode)) { pendingResult.finish() }
}
}
Timber.v("resultcode: ${pendingResult.resultCode}")
when (pendingResult.resultCode) {
// TODO notify about delivery
Activity.RESULT_OK -> markDelivered.execute(messageId) { pendingResult.finish() }
// TODO notify about delivery failure
else ->
markDeliveryFailed.execute(MarkDeliveryFailed.Params(messageId, resultCode)) {
pendingResult.finish()
}
}
} ?: let { Timber.e("couldn't get message id") }
}
}
@@ -0,0 +1,67 @@
/*
* 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.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkArchived
import dev.octoshrimpy.quik.interactor.MarkSeen
import dev.octoshrimpy.quik.interactor.MarkRead
import timber.log.Timber
import javax.inject.Inject
class MessageMarkReceiver : BroadcastReceiver() {
enum class MarkType {
Seen,
Read,
Archived
}
@Inject lateinit var markSeen: MarkSeen
@Inject lateinit var markRead: MarkRead
@Inject lateinit var markArchived: MarkArchived
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
intent.getLongExtra("threadId", 0).takeIf { it > 0 }?.let { threadId ->
intent.getIntExtra("type", -1).takeIf { it >= 0 }?.let { type ->
val pendingResult = goAsync()
when (type) {
MarkType.Seen.ordinal -> markSeen.execute(threadId) {
pendingResult.finish()
}
MarkType.Read.ordinal -> markRead.execute(listOf(threadId)) {
pendingResult.finish()
}
MarkType.Archived.ordinal -> markArchived.execute(listOf(threadId)) {
pendingResult.finish()
}
}
} ?:let { Timber.e("didn't get a valid type") }
} ?:let { Timber.e("didn't get a valid thread id") }
}
}
@@ -0,0 +1,79 @@
/*
* 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.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.klinker.android.send_message.MmsSentReceiver.EXTRA_FILE_PATH
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkFailed
import dev.octoshrimpy.quik.interactor.MarkSent
import dev.octoshrimpy.quik.repository.MessageRepository
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class MessageSentReceiver : BroadcastReceiver() {
companion object {
const val EXTRA_QUIK_MESSAGE_ID = "messageId"
const val EXTRA_IS_NOTIFY = "isNotify"
}
@Inject lateinit var markSent: MarkSent
@Inject lateinit var markFailed: MarkFailed
@Inject lateinit var messageRepo: MessageRepository
override fun onReceive(context: Context?, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
// if have EXTRA_FILE_PATH then need to delete mms cache file
intent.extras?.getString(EXTRA_FILE_PATH)?.let { filePath ->
Timber.v("delete mms temp file $filePath")
File(filePath).delete()
}
if (intent.extras?.getInt(EXTRA_IS_NOTIFY, -1) != -1) {
Timber.v("notify message sent resultcode $resultCode")
return
}
intent.extras?.getLong(EXTRA_QUIK_MESSAGE_ID)?.takeIf { it > 0 }
?.let { messageId ->
Timber.v("resultcode: $resultCode")
val pendingResult = goAsync()
when (pendingResult.resultCode) {
Activity.RESULT_OK ->
markSent.execute(messageId) { pendingResult.finish() }
else -> markFailed.execute(
MarkFailed.Params(messageId, pendingResult.resultCode)
) {
pendingResult.finish()
}
}
} ?: let { Timber.e("couldn't get message id") }
}
}
@@ -1,45 +1,88 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
* Copyright (C) 2015 Jacob Klinker
*
* This file is part of QKSMS.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* QKSMS is free software: you can redistribute it and/or modify
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* modifications from original:
* 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.
*
* QKSMS is distributed in the hope that it will be useful,
* 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
* along with QUIK. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.klinker.android.send_message.MmsReceivedReceiver
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.ReceiveMms
import javax.inject.Inject
import android.os.Parcelable
import android.telephony.SmsManager
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_FILE_PATH
import com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_LOCATION_URL
import com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_URI
import com.klinker.android.send_message.MmsReceivedReceiver.SUBSCRIPTION_ID
import com.klinker.android.send_message.Utils
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_FILE_PATH
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_LOCATION_URL
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_MMS_HTTP_STATUS
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_URI
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_SUBSCRIPTION_ID
import timber.log.Timber
class MmsReceivedReceiver : MmsReceivedReceiver() {
class MmsReceivedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Timber.v("mms downloaded. create worker to process")
@Inject lateinit var receiveMms: ReceiveMms
override fun onReceive(context: Context?, intent: Intent?) {
AndroidInjection.inject(this, context)
super.onReceive(context, intent)
}
override fun onMessageReceived(messageUri: Uri?) {
messageUri?.let { uri ->
val pendingResult = goAsync()
receiveMms.execute(uri) { pendingResult.finish() }
}
// start worker with message id as param
WorkManager.getInstance(context).enqueue(
OneTimeWorkRequestBuilder<ReceiveMmsWorker>()
.setInputData(
workDataOf(
INPUT_DATA_SUBSCRIPTION_ID to intent.getIntExtra(
SUBSCRIPTION_ID,
Utils.getDefaultSubscriptionId()
),
INPUT_DATA_EXTRA_FILE_PATH to intent.getStringExtra(EXTRA_FILE_PATH),
INPUT_DATA_EXTRA_LOCATION_URL to intent.getStringExtra(EXTRA_LOCATION_URL),
INPUT_DATA_EXTRA_MMS_HTTP_STATUS to intent.getIntExtra(
SmsManager.EXTRA_MMS_HTTP_STATUS,
0
),
INPUT_DATA_EXTRA_URI to
(intent.getParcelableExtra<Parcelable>(EXTRA_URI) as Uri?)?.toString()
)
)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
)
}
}
@@ -1,93 +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.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Telephony
import com.google.android.mms.MmsException
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.Transaction
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.SyncMessage
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class MmsSentReceiver : BroadcastReceiver() {
@Inject lateinit var syncMessage: SyncMessage
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("MMS sending result: $resultCode")
val uri = Uri.parse(intent.getStringExtra(Transaction.EXTRA_CONTENT_URI))
Timber.v(uri.toString())
when (resultCode) {
Activity.RESULT_OK -> {
Timber.v("MMS has finished sending, marking it as so in the database")
val values = ContentValues(1)
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT)
SqliteWrapper.update(context, context.contentResolver, uri, values, null, null)
}
else -> {
Timber.v("MMS has failed to send, marking it as so in the database")
try {
val messageId = ContentUris.parseId(uri)
val values = ContentValues(1)
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_FAILED)
SqliteWrapper.update(context, context.contentResolver, Telephony.Mms.CONTENT_URI, values,
"${Telephony.Mms._ID} = ?", arrayOf(messageId.toString()))
// TODO this query isn't able to find any results
// Need to figure out why the message isn't appearing in the PendingMessages Uri,
// so that we can properly assign the error type
val errorTypeValues = ContentValues(1)
errorTypeValues.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE,
Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT)
SqliteWrapper.update(context, context.contentResolver, Telephony.MmsSms.PendingMessages.CONTENT_URI,
errorTypeValues, "${Telephony.MmsSms.PendingMessages.MSG_ID} = ?",
arrayOf(messageId.toString()))
} catch (e: MmsException) {
e.printStackTrace()
}
}
}
val filePath = intent.getStringExtra(Transaction.EXTRA_FILE_PATH)
Timber.v(filePath)
File(filePath).delete()
Uri.parse(intent.getStringExtra("content_uri"))?.let { uri ->
val pendingResult = goAsync()
syncMessage.execute(uri) { pendingResult.finish() }
}
}
}
@@ -20,4 +20,4 @@ package dev.octoshrimpy.quik.receiver
import com.android.mms.transaction.PushReceiver
class MmsReceiver : PushReceiver()
class MmsWapPushReceiver : PushReceiver()
@@ -25,17 +25,16 @@ import androidx.core.app.RemoteInput
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.compat.SubscriptionManagerCompat
import dev.octoshrimpy.quik.interactor.MarkRead
import dev.octoshrimpy.quik.interactor.SendMessage
import dev.octoshrimpy.quik.interactor.SendNewMessage
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import javax.inject.Inject
class RemoteMessagingReceiver : BroadcastReceiver() {
@Inject lateinit var conversationRepo: ConversationRepository
@Inject lateinit var markRead: MarkRead
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var sendNewMessage: SendNewMessage
@Inject lateinit var subscriptionManager: SubscriptionManagerCompat
override fun onReceive(context: Context, intent: Intent) {
@@ -45,16 +44,23 @@ class RemoteMessagingReceiver : BroadcastReceiver() {
val bundle = intent.extras ?: return
val threadId = bundle.getLong("threadId")
val body = remoteInput.getCharSequence("body").toString()
markRead.execute(listOf(threadId))
val lastMessage = messageRepo.getMessages(threadId).lastOrNull()
val subId = subscriptionManager.activeSubscriptionInfoList
.firstOrNull { it.subscriptionId == lastMessage?.subId }
?.subscriptionId ?: -1
val addresses = conversationRepo.getConversation(threadId)?.recipients?.map { it.address } ?: return
val conversation = conversationRepo.getConversation(threadId)
val pendingRepository = goAsync()
sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body)) { pendingRepository.finish() }
sendNewMessage.execute(
SendNewMessage.Params(
subscriptionManager.activeSubscriptionInfoList
.firstOrNull { it.subscriptionId == lastMessage?.subId }
?.subscriptionId ?: -1,
0,
conversation?.recipients?.map { it.address } ?: return,
remoteInput.getCharSequence("body").toString(),
conversation.sendAsGroup
)
) { pendingRepository.finish() }
}
}
@@ -0,0 +1,22 @@
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.SendExistingMessage
import javax.inject.Inject
class ResendMessageReceiver : BroadcastReceiver() {
@Inject
lateinit var sendExistingMessage: SendExistingMessage
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val messageId = intent.getLongExtra("id", -1L)
val pendingRepository = goAsync()
sendExistingMessage.execute(messageId) { pendingRepository.finish() }
}
}
@@ -21,26 +21,31 @@ package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.SyncMessage
import dev.octoshrimpy.quik.interactor.ActionDelayedMessage
import timber.log.Timber
import javax.inject.Inject
class MmsUpdatedReceiver : BroadcastReceiver() {
class SendDelayedMessageReceiver : BroadcastReceiver() {
companion object {
const val URI = "uri"
const val MESSAGE_ID_EXTRA = "messageId"
}
@Inject lateinit var syncMessage: SyncMessage
@Inject lateinit var actionDelayedMessage: ActionDelayedMessage
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
intent.getStringExtra(URI)?.let { uriString ->
val pendingResult = goAsync()
syncMessage.execute(Uri.parse(uriString)) { pendingResult.finish() }
}
Timber.v("received")
intent.extras?.getLong(MESSAGE_ID_EXTRA)?.takeIf { it > 0 }
?.let { messageId ->
val result = goAsync()
actionDelayedMessage.execute(
ActionDelayedMessage.Params(messageId, ActionDelayedMessage.Action.Send)
) { result.finish() }
}
}
}
}
@@ -24,6 +24,7 @@ import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.SendScheduledMessage
import dev.octoshrimpy.quik.repository.MessageRepository
import timber.log.Timber
import javax.inject.Inject
class SendScheduledMessageReceiver : BroadcastReceiver() {
@@ -34,6 +35,8 @@ class SendScheduledMessageReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
intent.getLongExtra("id", -1L).takeIf { it >= 0 }?.let { id ->
val result = goAsync()
sendScheduledMessage.execute(id) { result.finish() }
@@ -1,43 +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.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.RetrySending
import dev.octoshrimpy.quik.repository.MessageRepository
import javax.inject.Inject
class SendSmsReceiver : BroadcastReceiver() {
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var retrySending: RetrySending
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val messageId = intent.getLongExtra("id", -1L).takeIf { it >= 0 } ?: return
val result = goAsync()
retrySending.execute(messageId) { result.finish() }
}
}
@@ -43,13 +43,11 @@ class SmsProviderChangedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
// Obtain the uri for the changed data
// If the value is null, don't continue
val uri = intent.data ?: return
// Sync the message to our realm
val pendingResult = goAsync()
syncMessage.execute(uri) { pendingResult.finish() }
syncMessage.execute(SyncMessage.Params(intent.data ?: return)) {
pendingResult.finish()
}
}
}
@@ -35,7 +35,7 @@ import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import javax.inject.Inject
class SmsReceiver : BroadcastReceiver() {
class SmsReceivedReceiver : BroadcastReceiver() {
@Inject lateinit var messageRepo: MessageRepository
override fun onReceive(context: Context, intent: Intent) {
@@ -1,53 +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.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkFailed
import dev.octoshrimpy.quik.interactor.MarkSent
import javax.inject.Inject
class SmsSentReceiver : BroadcastReceiver() {
@Inject lateinit var markSent: MarkSent
@Inject lateinit var markFailed: MarkFailed
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val id = intent.getLongExtra("id", 0L)
when (resultCode) {
Activity.RESULT_OK -> {
val pendingResult = goAsync()
markSent.execute(id) { pendingResult.finish() }
}
else -> {
val pendingResult = goAsync()
markFailed.execute(MarkFailed.Params(id, resultCode)) { pendingResult.finish() }
}
}
}
}
@@ -23,6 +23,7 @@ import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.util.nonDebugPackageName
class StartActivityFromWidgetReceiver : BroadcastReceiver() {
// why does this shim class exist rather than the widget launching activities more directly?
@@ -51,7 +52,7 @@ class StartActivityFromWidgetReceiver : BroadcastReceiver() {
}
context.startActivity(
Intent(context, Class.forName(context.packageName + activityToStartName))
Intent(context, Class.forName(nonDebugPackageName(context.packageName) + activityToStartName))
.setFlags(FLAG_ACTIVITY_NEW_TASK)
.putExtra("threadId", intent.getLongExtra("threadId", 0L))
)
@@ -128,7 +128,7 @@ class ContactRepositoryImpl @Inject constructor(
}
}
.map { contacts ->
contacts.sortedWith(Comparator { c1, c2 ->
contacts.sortedWith { c1, c2 ->
val initial = c1.name.firstOrNull()
val other = c2.name.firstOrNull()
if (initial?.isLetter() == true && other?.isLetter() != true) {
@@ -138,7 +138,7 @@ class ContactRepositoryImpl @Inject constructor(
} else {
c1.name.compareTo(c2.name, ignoreCase = true)
}
})
}
}
}
@@ -41,6 +41,7 @@ import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Case
import io.realm.Realm
import io.realm.RealmQuery
import io.realm.RealmResults
import io.realm.Sort
import java.util.concurrent.TimeUnit
@@ -53,17 +54,20 @@ class ConversationRepositoryImpl @Inject constructor(
private val cursorToRecipient: CursorToRecipient,
private val phoneNumberUtils: PhoneNumberUtils
) : ConversationRepository {
override fun getConversations(unreadAtTop: Boolean, archived: Boolean): RealmResults<Conversation> {
val sortOrder: MutableList<String> = arrayListOf("pinned", "draft", "lastMessage.date")
val sortDirections: MutableList<Sort> = arrayListOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
private fun getConversationsBase(
realm: Realm,
unreadAtTop: Boolean,
archived: Boolean
): RealmQuery<Conversation> {
val sortOrder = mutableListOf("pinned", "draft", "lastMessage.date")
val sortDirections = mutableListOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
if (unreadAtTop) {
sortOrder.add(0, "lastMessage.read")
sortDirections.add(0, Sort.ASCENDING)
}
return Realm.getDefaultInstance()
return realm
.where(Conversation::class.java)
.notEqualTo("id", 0L)
.equalTo("archived", archived)
@@ -74,39 +78,22 @@ class ConversationRepositoryImpl @Inject constructor(
.or()
.isNotEmpty("draft")
.endGroup()
.sort(
sortOrder.toTypedArray(),
sortDirections.toTypedArray()
)
.findAllAsync()
.sort(sortOrder.toTypedArray(), sortDirections.toTypedArray())
}
override fun getConversationsSnapshot(unreadAtTop: Boolean): List<Conversation> {
val sortOrder: MutableList<String> = arrayListOf("pinned", "draft", "lastMessage.date")
val sortDirections: MutableList<Sort> = arrayListOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
override fun getConversations(
unreadAtTop: Boolean,
archived: Boolean
): RealmResults<Conversation> =
getConversationsBase(Realm.getDefaultInstance(), unreadAtTop, archived)
.findAllAsync()
if (unreadAtTop) {
sortOrder.add(0, "lastMessage.read")
sortDirections.add(0, Sort.ASCENDING)
}
return Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.notEqualTo("id", 0L)
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.beginGroup()
.isNotNull("lastMessage")
.or()
.isNotEmpty("draft")
.endGroup()
.sort(sortOrder.toTypedArray(), sortDirections.toTypedArray())
override fun getConversationsSnapshot(unreadAtTop: Boolean): List<Conversation> =
Realm.getDefaultInstance().use { realm ->
getConversationsBase(realm, unreadAtTop, false)
.findAll()
.let(realm::copyFromRealm)
}
}
override fun getTopConversations() =
Realm.getDefaultInstance().use { realm ->
@@ -116,34 +103,42 @@ class ConversationRepositoryImpl @Inject constructor(
.beginGroup()
.equalTo("pinned", true)
.or()
.greaterThan("lastMessage.date", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
.greaterThan(
"lastMessage.date",
System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7)
)
.endGroup()
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.findAll()
.let(realm::copyFromRealm)
.sortedWith(compareByDescending<Conversation> { conversation -> conversation.pinned }
.sortedWith(compareByDescending<Conversation> {
conversation -> conversation.pinned
}
.thenByDescending { conversation ->
realm.where(Message::class.java)
.equalTo("threadId", conversation.id)
.greaterThan("date", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
.greaterThan(
"date",
System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7)
)
.count()
}
}
)
}
override fun setConversationName(id: Long, name: String) =
Completable.fromAction {
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.where(Conversation::class.java)
.equalTo("id", id)
.findFirst()
?.name = name
}
override fun setConversationName(id: Long, name: String) =
Completable.fromAction {
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.where(Conversation::class.java)
.equalTo("id", id)
.findFirst()
?.name = name
}
}.subscribeOn(Schedulers.io()) // Ensure the operation is performed on a background thread
}
}.subscribeOn(Schedulers.io()) // Ensure the operation is performed on a background thread
override fun searchConversations(query: CharSequence): List<SearchResult> {
val realm = Realm.getDefaultInstance()
@@ -166,7 +161,6 @@ class ConversationRepositoryImpl @Inject constructor(
.contains("parts.text", normalizedQuery, Case.INSENSITIVE)
.endGroup()
.findAll())
.asSequence()
.groupBy { message -> message.threadId }
.filter { (threadId, _) -> conversations.firstOrNull { it.id == threadId } != null }
.map { (threadId, messages) -> Pair(conversations.first { it.id == threadId }, messages.size) }
@@ -179,7 +173,7 @@ class ConversationRepositoryImpl @Inject constructor(
return conversations
.filter { conversation -> conversationFilter.filter(conversation, normalizedQuery) }
.map {
conversation -> SearchResult(normalizedQuery, conversation, 0)
conversation -> SearchResult(normalizedQuery, conversation, 0)
} + messagesByConversation
}
@@ -210,11 +204,25 @@ class ConversationRepositoryImpl @Inject constructor(
.findFirstAsync()
override fun getConversation(threadId: Long) =
Realm.getDefaultInstance()
.apply { refresh() }
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
tryOrNull(true) {
Realm.getDefaultInstance()
.apply { refresh() }
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
}
override fun updateSendAsGroup(threadId: Long, sendAsGroup: Boolean) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
?.let { conversation ->
realm.executeTransaction { conversation.sendAsGroup = sendAsGroup }
}
}
override fun getUnseenIds(archived: Boolean) =
ArrayList<Long>().apply {
@@ -291,7 +299,7 @@ class ConversationRepositoryImpl @Inject constructor(
override fun getRecipients(): RealmResults<Recipient> =
Realm.getDefaultInstance()
.where(Recipient::class.java)
.findAll()
.findAll()
override fun getUnmanagedRecipients(): Observable<List<Recipient>> =
Realm.getDefaultInstance().let { realm ->
@@ -310,39 +318,34 @@ class ConversationRepositoryImpl @Inject constructor(
.equalTo("id", recipientId)
.findFirst()
override fun getConversation(recipient: String) =
getConversation(listOf(recipient))
override fun createConversation(threadId: Long, sendAsGroup: Boolean) =
createConversationFromCp(threadId, sendAsGroup)
override fun getConversation(recipients: Collection<String>): Conversation? =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.findAll()
.asSequence()
.filter { conversation -> conversation.recipients.size == recipients.size }
.find { conversation ->
conversation.recipients.map { it.address }.all { address ->
recipients.any { recipient -> phoneNumberUtils.compare(recipient, address) }
conversation.recipients.map { it.address }.all { recipientAddress ->
recipients.any { phoneNumberUtils.compare(it, recipientAddress) }
}
}
?.let { realm.copyFromRealm(it) }
}
override fun getOrCreateConversation(threadId: Long) =
tryOrNull(true) {
getConversation(threadId) ?: createConversationFromCp(threadId)
}
override fun createConversation(addresses: Collection<String>, sendAsGroup: Boolean) =
TelephonyCompat.getOrCreateThreadId(context, addresses.toSet())
.takeIf { it != 0L }
?.let { providerThreadId -> createConversationFromCp(providerThreadId, sendAsGroup) }
override fun getOrCreateConversation(address: String) =
getOrCreateConversation(listOf(address))
override fun getOrCreateConversation(threadId: Long, sendAsGroup: Boolean) =
getConversation(threadId) ?: createConversation(threadId, sendAsGroup)
override fun getOrCreateConversation(addresses: Collection<String>) =
tryOrNull(true) {
getConversation(addresses)
?: tryOrNull { TelephonyCompat.getOrCreateThreadId(context, addresses.toSet()) }
?.takeIf { it != 0L }
?.let { threadId -> getOrCreateConversation(threadId) }
}
override fun getOrCreateConversation(addresses: Collection<String>, sendAsGroup: Boolean) =
getConversation(addresses) ?: createConversation(addresses, sendAsGroup)
override fun saveDraft(threadId: Long, draft: String) =
Realm.getDefaultInstance().use { realm ->
@@ -358,24 +361,31 @@ class ConversationRepositoryImpl @Inject constructor(
}
}
override fun updateConversations(vararg threadIds: Long) =
override fun updateConversations(threadIds: Collection<Long>) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
threadIds.forEach { threadId ->
val conversation = realm
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst() ?: return@forEach
realm.where(Conversation::class.java)
.anyOf("id", threadIds.toLongArray())
.findAll()
?.map { conversation ->
Pair(
conversation,
realm.where(Message::class.java)
.equalTo("threadId", conversation.id)
.sort("date", Sort.DESCENDING)
.findFirst()
)
}
?.let { conversationAndMessages ->
realm.executeTransaction {
conversationAndMessages.forEach { (conversation, message) ->
conversation.lastMessage = message
}
}
}
val message = realm
.where(Message::class.java)
.equalTo("threadId", threadId)
.sort("date", Sort.DESCENDING)
.findFirst()
realm.executeTransaction { conversation.lastMessage = message }
}
Unit
}
override fun markArchived(vararg threadIds: Long) =
@@ -387,10 +397,10 @@ class ConversationRepositoryImpl @Inject constructor(
realm.executeTransaction { conversations.forEach { it.archived = true } }
}
override fun markUnarchived(vararg threadIds: Long) =
override fun markUnarchived(threadIds: Collection<Long>) =
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.anyOf("id", threadIds.toLongArray())
.findAll()
realm.executeTransaction { conversations.forEach { it.archived = false } }
@@ -476,7 +486,7 @@ class ConversationRepositoryImpl @Inject constructor(
* we can return a [Conversation]. On some devices, the ContentProvider won't return the
* conversation unless it contains at least 1 message
*/
private fun createConversationFromCp(threadId: Long) =
private fun createConversationFromCp(threadId: Long, sendAsGroup: Boolean) =
tryOrNull(true) {
cursorToConversation.getConversationsCursor()
?.map(cursorToConversation::map)
@@ -507,6 +517,11 @@ class ConversationRepositoryImpl @Inject constructor(
conversation.apply {
recipients.clear()
recipients.addAll(matchedRecipients)
this.sendAsGroup =
if (recipients.size <= 1) false
else sendAsGroup
lastMessage = realm.where(Message::class.java)
.equalTo("threadId", threadId)
.sort("date", Sort.DESCENDING)
@@ -517,4 +532,5 @@ class ConversationRepositoryImpl @Inject constructor(
}
}
}
}
@@ -18,6 +18,7 @@
*/
package dev.octoshrimpy.quik.repository
import com.moez.QKSMS.manager.QkTransaction
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.ContentUris
@@ -35,33 +36,36 @@ import android.telephony.SmsManager
import android.webkit.MimeTypeMap
import androidx.core.content.contentValuesOf
import com.google.android.mms.ContentType
import com.google.android.mms.MMSPart
import com.google.android.mms.pdu_alt.MultimediaMessagePdu
import com.google.android.mms.pdu_alt.PduPersister
import com.klinker.android.send_message.SmsManagerFactory
import com.klinker.android.send_message.StripAccents
import com.klinker.android.send_message.Transaction
import dev.octoshrimpy.quik.common.util.extensions.now
import dev.octoshrimpy.quik.compat.TelephonyCompat
import dev.octoshrimpy.quik.extensions.anyOf
import dev.octoshrimpy.quik.extensions.insertOrUpdate
import dev.octoshrimpy.quik.extensions.isImage
import dev.octoshrimpy.quik.extensions.isVideo
import dev.octoshrimpy.quik.extensions.map
import dev.octoshrimpy.quik.extensions.resourceExists
import dev.octoshrimpy.quik.manager.ActiveConversationManager
import dev.octoshrimpy.quik.manager.KeyManager
import dev.octoshrimpy.quik.mapper.CursorToMessage
import dev.octoshrimpy.quik.mapper.CursorToPart
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Conversation
import dev.octoshrimpy.quik.model.Message
import dev.octoshrimpy.quik.model.Message.Companion.TYPE_MMS
import dev.octoshrimpy.quik.model.Message.Companion.TYPE_SMS
import dev.octoshrimpy.quik.model.MmsPart
import dev.octoshrimpy.quik.receiver.SendSmsReceiver
import dev.octoshrimpy.quik.receiver.SmsDeliveredReceiver
import dev.octoshrimpy.quik.receiver.SmsSentReceiver
import dev.octoshrimpy.quik.receiver.MessageDeliveredReceiver
import dev.octoshrimpy.quik.receiver.MessageSentReceiver
import dev.octoshrimpy.quik.receiver.SendDelayedMessageReceiver
import dev.octoshrimpy.quik.receiver.SendDelayedMessageReceiver.Companion.MESSAGE_ID_EXTRA
import dev.octoshrimpy.quik.util.ImageUtils
import dev.octoshrimpy.quik.util.PhoneNumberUtils
import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.tryOrNull
import io.realm.Case
import io.realm.Realm
import io.realm.RealmList
import io.realm.RealmResults
import io.realm.Sort
import timber.log.Timber
@@ -79,6 +83,8 @@ open class MessageRepositoryImpl @Inject constructor(
private val prefs: Preferences,
private val syncRepository: SyncRepository,
private val reactions: EmojiReactionRepository,
private val cursorToMessage: CursorToMessage,
private val cursorToPart: CursorToPart,
) : MessageRepository {
companion object {
@@ -109,13 +115,25 @@ open class MessageRepositoryImpl @Inject constructor(
override fun getMessagesSync(threadId: Long, query: String): RealmResults<Message> =
getMessagesBase(threadId, query).findAll()
override fun getMessage(id: Long) =
override fun getMessage(messageId: Long) =
Realm.getDefaultInstance()
.also { it.refresh() }
.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
override fun getUnmanagedMessage(messageId: Long) =
Realm.getDefaultInstance().use { realm ->
getMessage(messageId)?.let(realm::copyFromRealm)
}
override fun getMessages(messageIds: Collection<Long>): RealmResults<Message> =
Realm.getDefaultInstance()
.also { it.refresh() }
.where(Message::class.java)
.anyOf("id", messageIds.toLongArray())
.findAll()
override fun getMessageForPart(id: Long) =
Realm.getDefaultInstance()
.where(Message::class.java)
@@ -128,12 +146,12 @@ open class MessageRepositoryImpl @Inject constructor(
.equalTo("threadId", threadId)
.beginGroup()
.beginGroup()
.equalTo("type", "sms")
.equalTo("type", TYPE_SMS)
.`in`("boxId", arrayOf(Sms.MESSAGE_TYPE_INBOX, Sms.MESSAGE_TYPE_ALL))
.endGroup()
.or()
.beginGroup()
.equalTo("type", "mms")
.equalTo("type", TYPE_MMS)
.`in`("boxId", arrayOf(Mms.MESSAGE_BOX_INBOX, Mms.MESSAGE_BOX_ALL))
.endGroup()
.endGroup()
@@ -199,6 +217,7 @@ open class MessageRepositoryImpl @Inject constructor(
part.isVideo() -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ->
MediaStore.Downloads.EXTERNAL_CONTENT_URI
else -> MediaStore.Files.getContentUri("external")
}
@@ -279,26 +298,20 @@ open class MessageRepositoryImpl @Inject constructor(
threadIds.chunked(TELEPHONY_UPDATE_CHUNK_SIZE).forEach {
// chunked for smaller where clause size
val values = contentValuesOf(Sms.SEEN to seen)
val whereClause ="${Sms.SEEN} = ${if (seen) 0 else 1} " +
val whereClause = "${Sms.SEEN} = ${if (seen) 0 else 1} " +
"and ${Sms.THREAD_ID} in (${it.joinToString(",")})"
// sms messages
tryOrNull(true) {
countUpdated += context.contentResolver.update(
Sms.CONTENT_URI,
values,
whereClause,
null
Sms.CONTENT_URI, values, whereClause, null
)
}
// mms messages
tryOrNull(true) {
countUpdated += context.contentResolver.update(
Mms.CONTENT_URI,
values,
whereClause,
null
Mms.CONTENT_URI, values, whereClause, null
)
}
}
@@ -327,10 +340,10 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
override fun markSeen(threadId: Long) =
override fun markSeen(threadIds: Collection<Long>) =
Realm.getDefaultInstance().use { realm ->
realm.where(Message::class.java)
.equalTo("threadId", threadId)
.anyOf("threadId", threadIds.toLongArray())
.equalTo("seen", false)
.findAll()
.let { messages ->
@@ -339,7 +352,7 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
}.run {
telephonyMarkSeenRead(true, null, listOf(threadId))
telephonyMarkSeenRead(true, null, threadIds)
}
override fun markRead(threadIds: Collection<Long>) =
@@ -360,7 +373,7 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
}.run {
telephonyMarkSeenRead(true, true, threadIds)
telephonyMarkSeenRead(seen = true, read = true, threadIds = threadIds)
}
}
?: 0
@@ -383,67 +396,70 @@ open class MessageRepositoryImpl @Inject constructor(
}
?: 0
override fun sendMessage(
subId: Int,
threadId: Long,
addresses: Collection<String>,
body: String,
attachments: Collection<Attachment>,
delay: Int
) {
val signedBody = when {
prefs.signature.get().isEmpty() -> body
body.isNotEmpty() -> body + '\n' + prefs.signature.get()
else -> prefs.signature.get()
private fun syncProviderMessage(uri: Uri, sendAsGroup: Boolean): Message? {
// if uri doesn't have valid type
val type = when {
uri.toString().contains(TYPE_MMS) -> TYPE_MMS
uri.toString().contains(TYPE_SMS) -> TYPE_SMS
else -> return null
}
val smsManager = subId.takeIf { it != -1 }
?.let(SmsManagerFactory::createSmsManager)
?: SmsManager.getDefault()
// if uri doesn't have a valid id, fail
val contentId = tryOrNull(false) { ContentUris.parseId(uri) } ?: return null
// We only care about stripping SMS
val strippedBody = when (prefs.unicode.get()) {
true -> StripAccents.stripAccents(signedBody)
false -> signedBody
val stableUri = when (type) {
TYPE_MMS -> ContentUris.withAppendedId(Mms.CONTENT_URI, contentId)
else -> ContentUris.withAppendedId(Sms.CONTENT_URI, contentId)
}
val parts = smsManager.divideMessage(strippedBody).orEmpty()
val forceMms = prefs.longAsMms.get() && parts.size > 1
return context.contentResolver.query(
stableUri, null, null, null, null
)?.use { cursor ->
// if there are no rows, return null. else, move to the first row
if (!cursor.moveToFirst())
return null
if (addresses.size == 1 && attachments.isEmpty() && !forceMms) { // SMS
if (delay > 0) { // With delay
val sendTime = System.currentTimeMillis() + delay
val message = insertSentSms(
subId,
threadId,
addresses.first(),
strippedBody,
sendTime
)
cursorToMessage.map(Pair(cursor, CursorToMessage.MessageColumns(cursor))).apply {
this.sendAsGroup = sendAsGroup
val intent = getIntentForDelayedSms(message.id)
if (isMms()) {
parts = RealmList<MmsPart>().apply {
addAll(
cursorToPart.getPartsCursor(contentId)
?.map { cursorToPart.map(it) }
.orEmpty()
)
}
}
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, sendTime, intent)
} else { // No delay
val message = insertSentSms(
subId,
threadId,
addresses.first(),
strippedBody, now()
)
sendSms(message)
insertOrUpdate()
}
} else { // MMS
val parts = arrayListOf<MMSPart>()
}
}
override fun sendNewMessages(
subId: Int, toAddresses: Collection<String>, body: String,
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int
): Collection<Message> {
Timber.v("sending message(s)")
val parts = mutableListOf<com.google.android.mms.MMSPart>()
if (attachments.isNotEmpty()) {
Timber.v("has attachments")
val smsManager = subId.takeIf { it != -1 }
?.let(SmsManagerFactory::createSmsManager)
?: SmsManager.getDefault()
val maxWidth = smsManager.carrierConfigValues
.getInt(SmsManager.MMS_CONFIG_MAX_IMAGE_WIDTH)
.takeIf { prefs.mmsSize.get() == -1 } ?: Int.MAX_VALUE
.takeIf { prefs.mmsSize.get() == -1 }
?: Int.MAX_VALUE
val maxHeight = smsManager.carrierConfigValues
.getInt(SmsManager.MMS_CONFIG_MAX_IMAGE_HEIGHT)
.takeIf { prefs.mmsSize.get() == -1 } ?: Int.MAX_VALUE
.takeIf { prefs.mmsSize.get() == -1 }
?: Int.MAX_VALUE
var remainingBytes = when (prefs.mmsSize.get()) {
-1 -> smsManager.carrierConfigValues.getInt(SmsManager.MMS_CONFIG_MAX_MESSAGE_SIZE)
@@ -451,10 +467,7 @@ open class MessageRepositoryImpl @Inject constructor(
else -> prefs.mmsSize.get() * 1024
} * 0.9 // Ugly, but buys us a bit of wiggle room
signedBody.takeIf { it.isNotEmpty() }?.toByteArray()?.let { bytes ->
remainingBytes -= bytes.size
parts += MMSPart("text", ContentType.TEXT_PLAIN, bytes)
}
remainingBytes -= body.takeIf { it.isNotEmpty() }?.toByteArray()?.size ?: 0
// Attach those that can't be compressed (ie. everything but images)
parts += attachments
@@ -464,16 +477,16 @@ open class MessageRepositoryImpl @Inject constructor(
.filter { it.uri.resourceExists(context) }
.map {
remainingBytes -= it.getResourceBytes(context).size
val mmsPart = MMSPart(
it.getName(context),
it.getType(context),
it.getResourceBytes(context)
)
val part = com.google.android.mms.MMSPart().apply {
MimeType = it.getType(context)
Name = it.getName(context)
Data = it.getResourceBytes(context)
}
// release the attachment hold on the image bytes so the GC can reclaim
it.releaseResourceBytes()
mmsPart
part
}
val imageBytesByAttachment = attachments
@@ -514,8 +527,11 @@ open class MessageRepositoryImpl @Inject constructor(
// too big, we'll need to try smaller and smaller values
val scale = maxBytes / originalBytes.size * (0.9 - attempts * 0.2)
if (scale <= 0) {
Timber.w("Failed to compress ${originalBytes.size / 1024
}Kb to ${maxBytes.toInt() / 1024}Kb")
Timber.w(
"Failed to compress ${
originalBytes.size / 1024
}Kb to ${maxBytes.toInt() / 1024}Kb"
)
return@forEach
}
@@ -526,234 +542,198 @@ open class MessageRepositoryImpl @Inject constructor(
attempts++
scaledBytes = when (attachment.getType(context) == "image/gif") {
true -> ImageUtils.getScaledGif(
context,
attachment.uri,
newWidth,
newHeight
context, attachment.uri, newWidth, newHeight
)
false -> ImageUtils.getScaledImage(
context,
attachment.uri,
newWidth,
newHeight
context, attachment.uri, newWidth, newHeight
)
}
Timber.d("Compression attempt $attempts: ${scaledBytes.size / 1024
}/${maxBytes.toInt() / 1024}Kb ($width*$height -> $newWidth*${
newHeight})")
Timber.d(
"Compression attempt $attempts: ${
scaledBytes.size / 1024
}/${maxBytes.toInt() / 1024}Kb ($width*$height -> $newWidth*${
newHeight
})"
)
// release the attachment hold on the image bytes so the GC can reclaim
attachment.releaseResourceBytes()
}
Timber.v("Compressed ${originalBytes.size / 1024}Kb to ${
scaledBytes.size / 1024}Kb with a target size of ${
maxBytes.toInt() / 1024}Kb in $attempts attempts")
Timber.v(
"Compressed ${originalBytes.size / 1024}Kb to ${
scaledBytes.size / 1024
}Kb with a target size of ${
maxBytes.toInt() / 1024
}Kb in $attempts attempts"
)
imageBytesByAttachment[attachment] = scaledBytes
}
}
imageBytesByAttachment.forEach { (attachment, bytes) ->
parts += when (attachment.getType(context) == "image/gif") {
true -> MMSPart(attachment.getName(context), ContentType.IMAGE_GIF, bytes)
false -> MMSPart(attachment.getName(context), ContentType.IMAGE_JPEG, bytes)
parts += com.google.android.mms.MMSPart().apply {
MimeType =
if (attachment.getType(context) == "image/gif") ContentType.IMAGE_GIF
else ContentType.IMAGE_JPEG
Name = attachment.getName(context)
Data = bytes
}
}
}
Timber.v("create os provider message")
// 3 stage sending process - stage 1, create records in os provider
val group = (sendAsGroup && (toAddresses.size > 1))
val messageUri = QkTransaction.createMessage(
context, subId, body, prefs.signature.get(),
toAddresses.map(phoneNumberUtils::normalizeNumber).toTypedArray(),
parts, group, prefs.longAsMms.get(), prefs.unicode.get()
)
if (messageUri == Uri.EMPTY) {
Timber.v("create os provider message failed")
return listOf()
}
val message = syncProviderMessage(messageUri, group)
if (message == null) {
Timber.v("sync message failed for uri $messageUri")
return listOf()
}
Timber.v("created message id ${message.id} from uri $messageUri")
if (delayMs > 0) { // if delaying
val sendTime = (now() + delayMs)
// set delay time on the db message
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.copyToRealmOrUpdate(message.apply { date = sendTime })
}
}
// We need to strip the separators from outgoing MMS, or else they'll appear to have
// sent and not go through
val transaction = Transaction(context)
val recipients = addresses.map(phoneNumberUtils::normalizeNumber)
transaction.sendNewMessage(
subId,
threadId,
recipients,
parts,
null,
null
)
// create alarm that will trigger sending the message
(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager)
.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, sendTime, getIntentForDelayedSms(message.id)
)
Timber.v("set ${delayMs}ms delay for message id ${message.id}")
return listOf(message)
}
// send now (message will be exploded, as required, and all sent)
return sendMessage(message)
}
override fun sendSms(message: Message) {
val smsManager = message.subId.takeIf { it != -1 }
?.let(SmsManagerFactory::createSmsManager)
?: SmsManager.getDefault()
override fun sendMessage(message: Message): Collection<Message> {
val retVal = mutableListOf<Message>()
val parts = smsManager.divideMessage(
if (prefs.unicode.get()) StripAccents.stripAccents(message.body)
else message.body
)
?: arrayListOf()
tryOrNull(true) {
// explode message if needed
val explodedMessages = QkTransaction.explodeMessage(
context, message.getUri(), message.sendAsGroup
).filter { explodedMessageUri -> (explodedMessageUri != Uri.EMPTY) }
try {
smsManager.sendMultipartTextMessage(
message.address,
null,
parts,
ArrayList(
parts.map {
PendingIntent.getBroadcast(
context,
message.id.toInt(),
Intent(context, SmsSentReceiver::class.java)
.putExtra("id", message.id),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
// if multiple messages to send, create each and recurse to send
if (explodedMessages.size > 1) {
explodedMessages.forEach { explodedMessageUri ->
val childMessage = syncProviderMessage(explodedMessageUri, message.sendAsGroup)
if (childMessage != null) {
Timber.v("created message id ${childMessage.id} from uri $explodedMessageUri")
retVal.addAll(sendMessage(childMessage))
}
),
ArrayList(
parts.map {
val pendingIntent = PendingIntent.getBroadcast(
context,
message.id.toInt(),
Intent(context, SmsDeliveredReceiver::class.java)
.putExtra("id", message.id),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
if (prefs.delivery.get()) pendingIntent else null
}
)
)
} catch (e: IllegalArgumentException) {
Timber.w(e, "Message body lengths: ${parts.map { it?.length }}")
markFailed(message.id, Telephony.MmsSms.ERR_TYPE_GENERIC)
}
}
else
Timber.e("sync failed for uri $explodedMessageUri")
}
override fun resendMms(message: Message) =
tryOrNull {
PduPersister.getPduPersister(context).load(message.getUri()) as MultimediaMessagePdu
}
?.let { pdu ->
Transaction(context).sendNewMessage(
message.subId,
message.threadId,
pdu.to.map { it.string }.filter { it.isNotBlank() },
message.parts.mapNotNull { part ->
val bytes = tryOrNull(false) {
context.contentResolver.openInputStream(part.getUri())?.use {
inputStream -> inputStream.readBytes()
}
} ?: return@mapNotNull null
// mark original message as sent
markSent(message.id)
} else {
markSending(message.id)
MMSPart(part.name.orEmpty(), part.type, bytes)
},
message.subject,
message.getUri()
)
// individual message to send, send it
val sentIntent = Intent(context, MessageSentReceiver::class.java)
.putExtra(MessageSentReceiver.EXTRA_QUIK_MESSAGE_ID, message.id)
val deliveryIntent =
if (prefs.delivery.get())
Intent(context, MessageDeliveredReceiver::class.java)
.putExtra(MessageDeliveredReceiver.EXTRA_QUIK_MESSAGE_ID, message.id)
else null
// use values from os provider to resend the message, except subId
if (!QkTransaction.sendMessage(context, message.getUri(), sentIntent, deliveryIntent))
Timber.e("message id ${message.id} not sent by smsmms")
}
?: Unit
override fun cancelDelayedSms(id: Long) =
retVal.add(message)
}
return retVal
}
override fun sendMessage(messageId: Long) =
getMessage(messageId)
?.let { message -> sendMessage(message) }
?: listOf()
override fun cancelDelayedSmsAlarm(messageId: Long) =
(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager)
.cancel(getIntentForDelayedSms(id))
.cancel(getIntentForDelayedSms(messageId))
private fun getIntentForDelayedSms(id: Long) =
private fun getIntentForDelayedSms(messageId: Long) =
PendingIntent.getBroadcast(
context,
id.toInt(),
Intent(context, SendSmsReceiver::class.java).putExtra("id", id),
messageId.toInt(),
Intent(context, SendDelayedMessageReceiver::class.java)
.putExtra(MESSAGE_ID_EXTRA, messageId),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
override fun insertSentSms(
subId: Int,
threadId: Long,
address: String,
body: String,
date: Long
): Message {
// Insert the message to Realm
val message = Message().apply {
this.threadId = threadId
this.address = address
this.body = body
this.date = date
this.subId = subId
override fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long)
: Message {
val threadId = TelephonyCompat.getOrCreateThreadId(context, address)
id = messageIds.newId()
boxId = Sms.MESSAGE_TYPE_OUTBOX
type = "sms"
read = true
seen = true
}
// Insert the message to the native content provider
// insert the message to the native content provider
val values = contentValuesOf(
Sms.ADDRESS to address,
Sms.BODY to body,
Sms.DATE to System.currentTimeMillis(),
Sms.READ to true,
Sms.SEEN to true,
Sms.TYPE to Sms.MESSAGE_TYPE_OUTBOX,
Sms.DATE_SENT to sentTime,
Sms.THREAD_ID to threadId
)
if (prefs.canUseSubId.get())
values.put(Sms.SUBSCRIPTION_ID, message.subId)
values.put(Sms.SUBSCRIPTION_ID, subId)
var uri: Uri?
var managedMessage: Message? = null
val providerContentId = context.contentResolver.insert(Sms.Inbox.CONTENT_URI, values)
?.let { insertedUri -> ContentUris.parseId(insertedUri) }
?: 0
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction { managedMessage = realm.copyToRealmOrUpdate(message) }
// Update the contentId after the message has been inserted to the content provider
// The message might have been deleted by now, so only proceed if it's valid
//
// do this after inserting the message because it might be slow, and we want the message
// to be inserted into Realm immediately. We don't need to do this after receiving one
uri = context.contentResolver.insert(Sms.CONTENT_URI, values)?.apply {
lastPathSegment?.toLong()?.let { id ->
realm.executeTransaction {
managedMessage?.takeIf { it.isValid }?.contentId = id
}
}
}
}
// On some devices, we can't obtain a threadId until after the first message is sent in a
// conversation. In this case, update the message's threadId after it gets added
// to the native ContentProvider
if (threadId == 0L)
uri?.let(syncRepository::syncMessage)
return message
}
override fun insertReceivedSms(
subId: Int,
address: String,
body: String,
sentTime: Long
): Message {
// Insert the message to Realm
// insert the message to Realm
val message = Message().apply {
id = messageIds.newId()
this.address = address
this.body = body
this.dateSent = sentTime
this.date = System.currentTimeMillis()
this.threadId = threadId
this.subId = subId
id = messageIds.newId()
threadId = TelephonyCompat.getOrCreateThreadId(context, address)
date = System.currentTimeMillis()
contentId = providerContentId
boxId = Sms.MESSAGE_TYPE_INBOX
type = "sms"
read = activeConversationManager.getActiveConversation() == threadId
type = TYPE_SMS
read = (activeConversationManager.getActiveConversation() == threadId)
}
// Insert the message to the native content provider
val values = contentValuesOf(
Sms.ADDRESS to address,
Sms.BODY to body,
Sms.DATE_SENT to sentTime
)
if (prefs.canUseSubId.get())
values.put(Sms.SUBSCRIPTION_ID, message.subId)
Realm.getDefaultInstance().use { realm ->
var managedMessage: Message? = null
realm.executeTransaction { managedMessage = realm.copyToRealmOrUpdate(message) }
@@ -790,12 +770,12 @@ open class MessageRepositoryImpl @Inject constructor(
/**
* Marks the message as sending, in case we need to retry sending it
*/
override fun markSending(id: Long) =
override fun markSending(messageId: Long) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
?.let { message ->
// Update the message in realm
@@ -820,62 +800,112 @@ open class MessageRepositoryImpl @Inject constructor(
Unit
}
override fun markSent(id: Long) =
override fun markSent(messageId: Long) {
Timber.v("mark message id $messageId as sent")
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.findFirst()
realm.where(Message::class.java).equalTo("id", messageId).findFirst()
?.let { message ->
// Update the message in realm
realm.executeTransaction { message.boxId = Sms.MESSAGE_TYPE_SENT }
if (message.isSms()) {
// update the message in realm
realm.executeTransaction { message.boxId = Sms.MESSAGE_TYPE_SENT }
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(Sms.TYPE to Sms.MESSAGE_TYPE_SENT),
null,
null
)
}
Unit
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(Sms.TYPE to Sms.MESSAGE_TYPE_SENT),
null,
null
)
} else {
// update the message in realm
realm.executeTransaction { message.boxId = Mms.MESSAGE_BOX_SENT }
override fun markFailed(id: Long, resultCode: Int) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.findFirst()
?.let { message ->
// Update the message in realm
realm.executeTransaction {
message.boxId = Sms.MESSAGE_TYPE_FAILED
message.errorCode = resultCode
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(Mms.MESSAGE_BOX to Mms.MESSAGE_BOX_SENT),
null,
null
)
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(
Sms.TYPE to Sms.MESSAGE_TYPE_FAILED,
Sms.ERROR_CODE to resultCode,
),
null,
null
)
}
Unit
}
}
override fun markFailed(messageId: Long, resultCode: Int) =
Realm.getDefaultInstance().use { realm ->
Timber.v("mark message id $messageId as failed. code $resultCode")
realm.refresh()
realm.where(Message::class.java).equalTo("id", messageId).findFirst()
?.let { message ->
if (message.isSms()) {
if (message.boxId != Sms.MESSAGE_TYPE_FAILED) {
// Update the message in realm
realm.executeTransaction {
message.boxId = Sms.MESSAGE_TYPE_FAILED
message.errorCode = resultCode
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(
Sms.TYPE to Sms.MESSAGE_TYPE_FAILED,
Sms.ERROR_CODE to resultCode,
),
null,
null
)
true
} else false
} else { // mms
if (message.boxId != Mms.MESSAGE_BOX_FAILED) {
// Update the message in realm
realm.executeTransaction {
message.boxId = Mms.MESSAGE_BOX_FAILED
message.errorCode = resultCode
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(
Mms.MESSAGE_BOX to Mms.MESSAGE_BOX_FAILED
),
null,
null
)
// TODO this query isn't able to find any results
// Need to figure out why the message isn't appearing in the PendingMessages Uri,
// so that we can properly assign the error type
context.contentResolver.update(
Telephony.MmsSms.PendingMessages.CONTENT_URI,
contentValuesOf(
Telephony.MmsSms.PendingMessages.ERROR_TYPE to Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT
),
"${Telephony.MmsSms.PendingMessages.MSG_ID} = ?",
arrayOf(message.id.toString())
)
true
} else false
}
} ?: false
}
override fun markDelivered(id: Long) =
override fun markDelivered(messageId: Long) =
Realm.getDefaultInstance().use { realm ->
Timber.v("mark message id $messageId as delivered")
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
?.let { message ->
// Update the message in realm
@@ -900,12 +930,14 @@ open class MessageRepositoryImpl @Inject constructor(
Unit
}
override fun markDeliveryFailed(id: Long, resultCode: Int) =
override fun markDeliveryFailed(messageId: Long, resultCode: Int) =
Realm.getDefaultInstance().use { realm ->
Timber.v("mark message id $messageId as delivery failed result code $resultCode")
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
?.let { message ->
// Update the message in realm
@@ -936,17 +968,18 @@ open class MessageRepositoryImpl @Inject constructor(
Realm.getDefaultInstance().use { realm ->
realm.refresh()
val messages = realm.where(Message::class.java)
realm.where(Message::class.java)
.anyOf("id", messageIds.toLongArray())
.findAll()
?.let { messages ->
messages.mapNotNull { message ->
val uri = message.getUri()
if (uri != Uri.EMPTY)
context.contentResolver.delete(uri, null, null)
}
val uris = messages.map { it.getUri() }
realm.executeTransaction { messages.deleteAllFromRealm() }
uris.forEach {
uri -> context.contentResolver.delete(uri, null, null)
}
realm.executeTransaction { messages.deleteAllFromRealm() }
} ?: Unit
}
override fun getOldMessageCounts(maxAgeDays: Int) =
@@ -979,3 +1012,4 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
}
@@ -190,6 +190,7 @@ class SyncRepositoryImpl @Inject constructor(
name = persistedConversation.name
blockingClient = persistedConversation.blockingClient
blockReason = persistedConversation.blockReason
sendAsGroup = persistedConversation.sendAsGroup
}
lastMessage = realm.where(Message::class.java)
.sort("date", Sort.DESCENDING)
@@ -246,33 +247,40 @@ class SyncRepositoryImpl @Inject constructor(
})
}
}
override fun syncMessage(uri: Uri): Message? {
override fun syncMessage(uri: Uri, messageId: Long): Message? {
// If we don't have a valid type, return null
val type = when {
uri.toString().contains("mms") -> "mms"
uri.toString().contains("sms") -> "sms"
uri.toString().contains(Message.TYPE_MMS) -> Message.TYPE_MMS
uri.toString().contains(Message.TYPE_SMS) -> Message.TYPE_SMS
else -> return null
}
// If we don't have a valid id, return null
val id = tryOrNull(false) { ContentUris.parseId(uri) } ?: return null
val contentId = tryOrNull(false) { ContentUris.parseId(uri) } ?: return null
// Check if the message already exists, so we can reuse the id
val existingId = Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("type", type)
.equalTo("contentId", id)
.findFirst()
?.id
.equalTo("type", type)
.equalTo("contentId", contentId)
.or()
.beginGroup()
.equalTo("id", messageId)
.and()
.equalTo("contentId", 0L)
.endGroup()
.findFirst()
?.id
}
// The uri might be something like content://mms/inbox/id
// The box might change though, so we should just use the mms/id uri
val stableUri = when (type) {
"mms" -> ContentUris.withAppendedId(Telephony.Mms.CONTENT_URI, id)
else -> ContentUris.withAppendedId(Telephony.Sms.CONTENT_URI, id)
Message.TYPE_MMS -> ContentUris.withAppendedId(Telephony.Mms.CONTENT_URI, contentId)
else -> ContentUris.withAppendedId(Telephony.Sms.CONTENT_URI, contentId)
}
return contentResolver.query(stableUri, null, null, null, null)?.use { cursor ->
@@ -18,13 +18,13 @@ import javax.inject.Inject
class AutoDeleteService : JobService() {
companion object {
private const val JobId = 8120235
private const val JOB_ID = 8120235
@SuppressLint("MissingPermission") // Added in [presentation]'s AndroidManifest.xml
fun scheduleJob(context: Context) {
Timber.i("Scheduling job")
val serviceComponent = ComponentName(context, AutoDeleteService::class.java)
val periodicJob = JobInfo.Builder(JobId, serviceComponent)
val periodicJob = JobInfo.Builder(JOB_ID, serviceComponent)
.setPeriodic(TimeUnit.DAYS.toMillis(1))
.setPersisted(true)
.build()
@@ -34,7 +34,7 @@ class AutoDeleteService : JobService() {
fun cancelJob(context: Context) {
Timber.i("Canceling job")
context.jobScheduler.cancel(JobId)
context.jobScheduler.cancel(JOB_ID)
}
}
@@ -23,24 +23,26 @@ import android.content.Intent
import android.net.Uri
import android.telephony.TelephonyManager
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.SendMessage
import dev.octoshrimpy.quik.interactor.SendNewMessage
import dev.octoshrimpy.quik.repository.ConversationRepository
import javax.inject.Inject
class HeadlessSmsSendService : IntentService("HeadlessSmsSendService") {
@Inject lateinit var conversationRepo: ConversationRepository
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var sendNewMessage: SendNewMessage
override fun onHandleIntent(intent: Intent?) {
if (intent?.action != TelephonyManager.ACTION_RESPOND_VIA_MESSAGE) return
AndroidInjection.inject(this)
intent.extras?.getString(Intent.EXTRA_TEXT)?.takeIf { it.isNotBlank() }?.let { body ->
val intentUri = intent.data
val recipients = intentUri?.let(::getRecipients)?.split(";") ?: return@let
val threadId = conversationRepo.getOrCreateConversation(recipients)?.id ?: 0L
sendMessage.execute(SendMessage.Params(-1, threadId, recipients, body))
val recipients = intent.data?.let(::getRecipients)?.split(";") ?: return@let
val conversation = conversationRepo.getOrCreateConversation(recipients)
sendNewMessage.execute(SendNewMessage.Params(
-1, 0, recipients, body, conversation?.sendAsGroup ?: false
))
}
}
@@ -1,7 +0,0 @@
package com.moez.QKSMS.util
class Constants {
companion object {
const val SAVED_MESSAGE_TEXT_FILE_PREFIX = "QuikSmsText-"
}
}
@@ -1,149 +0,0 @@
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
class FileUtils {
companion object {
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.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())
}
}
}
@@ -25,7 +25,7 @@ import java.io.File
class QkFileObserver(path: String) : FileObserver(path, CREATE or DELETE or MODIFY) {
private val subject = BehaviorSubject.createDefault<String>(path).toSerialized()
private val subject = BehaviorSubject.createDefault(path).toSerialized()
val observable: Observable<String> = subject
.doOnSubscribe { startWatching() }
@@ -26,8 +26,8 @@ import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.moez.QKSMS.manager.MediaRecorderManager
import com.moez.QKSMS.util.Constants
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import dev.octoshrimpy.quik.util.Constants
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@@ -77,6 +77,8 @@ class HousekeepingWorker(appContext: Context, workerParams: WorkerParameters)
removeSavedMessagesTexts(twoHoursAgo)
removeOrphanedComposeDelayCancelledAttachments(twoHoursAgo)
return Result.success()
}
@@ -87,7 +89,7 @@ class HousekeepingWorker(appContext: Context, workerParams: WorkerParameters)
// remove orphaned scheduled message dirs in files dir
File(applicationContext.filesDir,"")
// get dirs that match prefix 'scheduled-'
.listFiles { entry -> entry.isDirectory && entry.name.startsWith("scheduled-") }
.listFiles { entry -> entry.isDirectory && entry.name.startsWith(Constants.SCHEDULED_MESSAGE_FILE_PREFIX) }
// filter out any dirs that have an associated scheduled message in db
?.filterNot {
scheduledMessageIds.contains(it.name.substringAfter('-').toLong())
@@ -113,4 +115,12 @@ class HousekeepingWorker(appContext: Context, workerParams: WorkerParameters)
(entry.lastModified() < removeOlderThan)
}?.forEach { it.delete() } // delete message text file
private fun removeOrphanedComposeDelayCancelledAttachments(removeOlderThan: Long) =
// find dirs in cache dir
applicationContext.cacheDir.listFiles { entry ->
entry.isDirectory &&
entry.name.startsWith(Constants.DELAY_CANCELLED_CACHED_ATTACHMENTS_FILE_PREFIX)
(entry.lastModified() < removeOlderThan)
}?.forEach { it.deleteRecursively() } // recursively delete dir
}
@@ -23,15 +23,31 @@ import androidx.work.ListenableWorker
import androidx.work.Worker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import dev.octoshrimpy.quik.interactor.ReceiveSms
import dev.octoshrimpy.quik.blocking.BlockingClient
import dev.octoshrimpy.quik.interactor.UpdateBadge
import dev.octoshrimpy.quik.manager.ActiveConversationManager
import dev.octoshrimpy.quik.manager.NotificationManager
import dev.octoshrimpy.quik.manager.ShortcutManager
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import dev.octoshrimpy.quik.repository.SyncRepository
import dev.octoshrimpy.quik.util.Preferences
import javax.inject.Inject
class InjectionWorkerFactory @Inject constructor(
private val receiveSms: ReceiveSms,
private val scheduledMessageRepository: ScheduledMessageRepository
)
: WorkerFactory() {
private val conversationRepo: ConversationRepository,
private val blockingClient: BlockingClient,
private val prefs: Preferences,
private val messageRepo: MessageRepository,
private val updateBadge: UpdateBadge,
private val shortcutManager: ShortcutManager,
private val scheduledMessageRepository: ScheduledMessageRepository,
private val notificationManager: NotificationManager,
private val activeConversationManager: ActiveConversationManager,
private val syncRepo: SyncRepository,
) : WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
@@ -44,11 +60,27 @@ class InjectionWorkerFactory @Inject constructor(
.newInstance(appContext, workerParameters)
when (instance) {
is HousekeepingWorker -> {
is HousekeepingWorker ->
instance.scheduledMessageRepository = scheduledMessageRepository
}
is ReceiveSmsWorker -> {
instance.receiveSms = receiveSms
instance.conversationRepo = conversationRepo
instance.blockingClient = blockingClient
instance.prefs = prefs
instance.messageRepo = messageRepo
instance.shortcutManager = shortcutManager
instance.notificationManager = notificationManager
instance.updateBadge = updateBadge
}
is ReceiveMmsWorker -> {
instance.syncRepo = syncRepo
instance.activeConversationManager = activeConversationManager
instance.conversationRepo = conversationRepo
instance.blockingClient = blockingClient
instance.prefs = prefs
instance.messageRepo = messageRepo
instance.shortcutManager = shortcutManager
instance.notificationManager = notificationManager
instance.updateBadge = updateBadge
}
}
@@ -0,0 +1,353 @@
/*
* 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.worker
import android.app.PendingIntent
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Telephony
import androidx.core.net.toUri
import androidx.work.ForegroundInfo
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.android.mms.service_alt.DownloadRequest
import com.android.mms.service_alt.MmsConfig
import com.android.mms.service_alt.MmsConfig.Overridden
import com.android.mms.transaction.DownloadManager
import com.google.android.mms.pdu_alt.AcknowledgeInd
import com.google.android.mms.pdu_alt.EncodedStringValue
import com.google.android.mms.pdu_alt.NotificationInd
import com.google.android.mms.pdu_alt.NotifyRespInd
import com.google.android.mms.pdu_alt.PduComposer
import com.google.android.mms.pdu_alt.PduHeaders
import com.google.android.mms.pdu_alt.PduPersister
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.MmsSentReceiver
import com.klinker.android.send_message.SmsManagerFactory
import com.klinker.android.send_message.Utils
import dev.octoshrimpy.quik.blocking.BlockingClient
import dev.octoshrimpy.quik.interactor.UpdateBadge
import dev.octoshrimpy.quik.manager.ActiveConversationManager
import dev.octoshrimpy.quik.manager.NotificationManager
import dev.octoshrimpy.quik.manager.ShortcutManager
import dev.octoshrimpy.quik.receiver.MessageSentReceiver
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import dev.octoshrimpy.quik.repository.SyncRepository
import dev.octoshrimpy.quik.util.Preferences
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.UUID
import javax.inject.Inject
class ReceiveMmsWorker(appContext: Context, workerParams: WorkerParameters)
: Worker(appContext, workerParams) {
companion object {
const val INPUT_DATA_SUBSCRIPTION_ID = "subscriptionId"
const val INPUT_DATA_EXTRA_FILE_PATH = "filePath"
const val INPUT_DATA_EXTRA_LOCATION_URL = "locationUrl"
const val INPUT_DATA_EXTRA_MMS_HTTP_STATUS = "mmsHttpStatus"
const val INPUT_DATA_EXTRA_URI = "extraUri"
private const val LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?"
}
@Inject lateinit var activeConversationManager: ActiveConversationManager
@Inject lateinit var conversationRepo: ConversationRepository
@Inject lateinit var blockingClient: BlockingClient
@Inject lateinit var prefs: Preferences
@Inject lateinit var syncRepo: SyncRepository
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var notificationManager: NotificationManager
@Inject lateinit var updateBadge: UpdateBadge
@Inject lateinit var shortcutManager: ShortcutManager
override fun doWork(): Result {
Timber.v("started")
val subscriptionId = inputData.getInt(INPUT_DATA_SUBSCRIPTION_ID, -1)
val filePath = inputData.getString(INPUT_DATA_EXTRA_FILE_PATH) ?: ""
val locationUrl = inputData.getString(INPUT_DATA_EXTRA_LOCATION_URL) ?: ""
val extraUri = inputData.getString(INPUT_DATA_EXTRA_URI) ?: ""
if (filePath.isEmpty()) {
Timber.e("empty file path")
return Result.failure(inputData)
}
if (locationUrl.isEmpty()) {
Timber.e("empty location url")
return Result.failure(inputData)
}
if (extraUri.isEmpty()) {
Timber.e("empty extra uri")
return Result.failure(inputData)
}
Timber.v(filePath)
val downloadFile = File(filePath)
try {
// read file into a bytearray
val mmsData = FileInputStream(downloadFile).use { inputStream ->
val fileLength = downloadFile.length().toInt()
ByteArray(fileLength).let { bytes ->
inputStream.read(bytes, 0, fileLength)
bytes
}
}
Timber.v("response buffered length: ${mmsData.size}")
if (mmsData.isNotEmpty()) {
// build notification ind (beware this must be done prior to downloadrequest.persist)
val notificationInd =
PduPersister.getPduPersister(applicationContext).load(extraUri.toUri())
as NotificationInd
// persist message
val messageUri = DownloadRequest.persist(
applicationContext, mmsData,
Overridden(MmsConfig(applicationContext), null),
locationUrl, subscriptionId, null
)
handleHttpError(
applicationContext,
inputData.getInt(INPUT_DATA_EXTRA_MMS_HTTP_STATUS, 0),
locationUrl
)
DownloadManager.finishDownload(locationUrl)
// if message was persisted ok
if (messageUri != null) {
// Sync the message
val message = syncRepo.syncMessage(messageUri)
?: return Result.failure(inputData)
// 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))
}
// 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))
} else {
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
}
// update the conversation
conversationRepo.updateConversations(listOf(message.threadId))
val conversation =
conversationRepo.getOrCreateConversation(message.threadId)
?: return Result.failure(inputData)
// don't notify (continue) for blocked conversations
if (conversation.blocked) {
Timber.v("no notifications for blocked")
return Result.success(inputData)
}
// unarchive conversation if necessary
if (conversation.archived)
conversationRepo.markUnarchived(listOf(conversation.id))
// unarchive conversation if necessary
if (conversation.archived) {
Timber.v("conversation unarchived")
conversationRepo.markUnarchived(listOf(conversation.id))
}
// update/create notification
Timber.v("update/create notification")
notificationManager.update(conversation.id)
// update shortcuts
Timber.v("update shortcuts")
shortcutManager.updateShortcuts()
shortcutManager.reportShortcutUsed(conversation.id)
// update the badge and widget
Timber.v("update badge and widget")
updateBadge.execute(Unit)
}
// send ack to mmsc
sendAcknowledgeInd(applicationContext, subscriptionId, notificationInd)
// send notify ind to mmsc
sendNotifyRespInd(applicationContext, subscriptionId, notificationInd)
}
}
else Timber.e("empty mms data")
} catch (e: FileNotFoundException) {
Timber.e("file not found: ${e.message}")
} catch (e: IOException) {
Timber.e("io exception: ${e.message}")
} catch (e: Exception) {
Timber.e("mms receive worker exception: ${e.message}")
} finally {
downloadFile.delete()
}
Timber.v("finished")
return Result.success()
}
private fun handleHttpError(context: Context, mmsHttpStatus: Int, locationUrl: String) {
if ((mmsHttpStatus == 404) || (mmsHttpStatus == 400)) {
// Delete the corresponding NotificationInd
SqliteWrapper.delete(
context, context.contentResolver, Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
arrayOf(
PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND.toString(),
locationUrl
)
)
}
}
private fun sendResponsePdu(
context: Context, subscriptionId: Int, contentLocation: ByteArray, pduBytes: ByteArray
) {
// write pdu bytes to temporary file
val fileName = "send.notify.${UUID.randomUUID()}.dat"
val contentUri = Uri.Builder()
.authority("${context.packageName}.MmsFileProvider")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build()
try {
FileOutputStream(File(context.cacheDir, fileName)).use { outputStream ->
outputStream.write(pduBytes)
}
Timber.v("notify send file $fileName")
} catch (e: Exception) {
Timber.e("error writing notify send file", e)
}
val useWapMmsc = com.android.mms.MmsConfig.getNotifyWapMMSC()
if (useWapMmsc)
Timber.v("using content location for wap mmsc")
SmsManagerFactory.createSmsManager(subscriptionId).sendMultimediaMessage(
context, contentUri,
if (useWapMmsc) String(contentLocation) else null,
null,
PendingIntent.getBroadcast(
context, 0,
Intent(context, MessageSentReceiver::class.java)
.setData(contentUri) // this is only used to make pending intent unique
.putExtra(MmsSentReceiver.EXTRA_FILE_PATH, fileName)
.putExtra(MessageSentReceiver.EXTRA_IS_NOTIFY, 1),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
private fun sendAcknowledgeInd(
context: Context, subscriptionId: Int, notificationInd: NotificationInd
) {
Timber.v("create m-acknowledge.ind")
try {
// if the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK
if (notificationInd.transactionId != null) {
val ackInd = AcknowledgeInd(
PduHeaders.CURRENT_MMS_VERSION, notificationInd.transactionId
).apply {
// insert the 'from' address per spec
from = EncodedStringValue(Utils.getMyPhoneNumber(context).orEmpty())
}
val pdu = PduComposer(context, ackInd).make()
// pack m-acknowledge.ind and send it
sendResponsePdu(context, subscriptionId, notificationInd.contentLocation, pdu)
}
} catch (e: Exception) {
Timber.e("error creating m-acknowledge.ind", e)
}
}
private fun sendNotifyRespInd(
context: Context, subscriptionId: Int, notificationInd: NotificationInd
) {
Timber.v("create m-notifyresp.ind")
try {
if (notificationInd.transactionId != null) {
val notifyRespInd = NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
notificationInd.transactionId,
PduHeaders.STATUS_RETRIEVED
)
val pdu = PduComposer(context, notifyRespInd).make()
// pack m-notifyresp.ind and send it
sendResponsePdu(context, subscriptionId, notificationInd.contentLocation, pdu)
}
} catch (e: Exception) {
Timber.e("error creating m-notifyresp.ind", e)
}
}
override fun getForegroundInfo() = ForegroundInfo(
0,
notificationManager.getForegroundNotificationForWorkersOnOlderAndroids()
)
}
@@ -19,9 +19,16 @@
package dev.octoshrimpy.quik.worker
import android.content.Context
import androidx.work.ForegroundInfo
import androidx.work.Worker
import androidx.work.WorkerParameters
import dev.octoshrimpy.quik.interactor.ReceiveSms
import dev.octoshrimpy.quik.blocking.BlockingClient
import dev.octoshrimpy.quik.interactor.UpdateBadge
import dev.octoshrimpy.quik.manager.NotificationManager
import dev.octoshrimpy.quik.manager.ShortcutManager
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import dev.octoshrimpy.quik.util.Preferences
import timber.log.Timber
import javax.inject.Inject
@@ -31,23 +38,91 @@ class ReceiveSmsWorker(appContext: Context, workerParams: WorkerParameters)
const val INPUT_DATA_KEY_MESSAGE_ID = "messageId"
}
@Inject lateinit var receiveSms: ReceiveSms
@Inject lateinit var conversationRepo: ConversationRepository
@Inject lateinit var blockingClient: BlockingClient
@Inject lateinit var prefs: Preferences
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var notificationManager: NotificationManager
@Inject lateinit var updateBadge: UpdateBadge
@Inject lateinit var shortcutManager: ShortcutManager
override fun doWork(): Result {
Timber.v("started")
val messageId = inputData.getLong(INPUT_DATA_KEY_MESSAGE_ID, -1)
if (messageId == -1L) {
Timber.v("failed. message id was -1")
if (messageId < 0) {
Timber.v("failed. message id was {messageId}")
return Result.failure(inputData)
}
// process the new message
receiveSms.execute(messageId)
val message = messageRepo.getMessage(messageId) ?: return Result.failure(inputData)
val action = blockingClient.shouldBlock(message.address).blockingGet()
when {
((action is BlockingClient.Action.Block) && prefs.drop.get()) -> {
// blocked and 'drop blocked' remove from db and don't continue
Timber.v("address is blocked and drop blocked is on. dropped")
messageRepo.deleteMessages(listOf(message.id))
return Result.failure(inputData)
}
action is BlockingClient.Action.Block -> {
// blocked
Timber.v("address is blocked")
messageRepo.markRead(listOf(message.threadId))
conversationRepo.markBlocked(
listOf(message.threadId),
prefs.blockingManager.get(),
action.reason
)
}
action is BlockingClient.Action.Unblock -> {
// unblock
Timber.v("unblock conversation if blocked")
conversationRepo.markUnblocked(message.threadId)
}
}
// update and fetch conversation
conversationRepo.updateConversations(listOf(message.threadId))
val conversation = conversationRepo.getOrCreateConversation(message.threadId)
?: return Result.failure(inputData)
// don't notify (continue) for blocked conversations
if (conversation.blocked) {
Timber.v("no notifications for blocked")
return Result.failure(inputData)
}
// unarchive conversation if necessary
if (conversation.archived) {
Timber.v("conversation unarchived")
conversationRepo.markUnarchived(listOf(conversation.id))
}
// update/create notification
Timber.v("update/create notification")
notificationManager.update(conversation.id)
// update shortcuts
Timber.v("update shortcuts")
shortcutManager.updateShortcuts()
shortcutManager.reportShortcutUsed(conversation.id)
// update the badge and widget
Timber.v("update badge and widget")
updateBadge.execute(Unit)
Timber.v("finished")
return Result.success()
}
override fun getForegroundInfo() = ForegroundInfo(
0,
notificationManager.getForegroundNotificationForWorkersOnOlderAndroids()
)
}